Search code examples
javascriptrelationships

Best practice for maintaining relationships in js between groups of elements


So you have one list and another. One is used for navigation, the other meta data.

Now, the idea is that a user will be adding, reordering, and deleting items in the nav list, and the meta list should be updated to reflect what's going on in the nav list. By adding an item to the nav list, a chunk of HTML is appended to the meta list.

Keep in mind I'll be using jQuery.

So the thing im questioning is the best way to establish relationships between the sets of elements. Now I realize I can use indexes and :eq() etc, but in a complicated implementation with lots of containers, things can get hairy... and coming back months or years down the road to do maintenance could be painful.

Just wondering if people had suggestions for establishing clear relationships. Storing id's in hidden fields? Some kind of master array?


Solution

  • The way you are thinking about this will likely produce some spaghetti looking code. I highly recommend you take a look at an MVC framework like backbone.js < http://documentcloud.github.com/backbone/ > Backbone has a powerful event model that will make it easy for one chunk of UI code to broadcast events to other chunks of UI code.

    Using backbone, you could use a model to track the state of your items. You can then have modular views "subscribe" to add/remove/change events on the model.

    Backbone literally was built to solve the problem you are facing with your app: "how do I keep track of the state of all of my objects? When they change, how do I track the subsequent UI changes?"

    Hope this helps