Updating changed attributes with backbone.js

18,081

If your view is only showing a single attribute - for example, if it's a checkbox showing some boolean attribute of your model - you should listen to the 'change:attribute_name' event for that attribute, as described in the Backbone docs.

If your view is more complex and relies on multiple model attributes - for example if it's a view for "To Do" list item that has "done", "text", and "dueDate" elements, then listen for the 'change' event. In this case, you can either either choose to update all of the elements on each event, or you can use changedAttributes() to determine which elements need updating.

To illustrate ...

Update attributes using 'change:attribute_name' events:

This style works well for simple views where the number of model attributes being rendered is < 3 or so. More than that and the code gets a bit cumbersome.

model.bind('change:done', function() {
    view.doneElement.checked = model.get('done');
});
model.bind('change:text', function() {
    view.textElement.value = model.get('text');
});
model.bind('change:dueDate', function() {
    view.dueDateElement.value = model.get('dueDate');
});

Update everything on 'change' events:

This style works well for complex views that render 4 or more attributes (the 3/4 attribute count is just a rough guideline, based mostly on my personal opinion).

model.bind('change', function() {
    view.doneElement.checked = model.get('done');
    view.textElement.value = model.get('text');
    view.dueDateElement.value = model.get('dueDate');
});

The downside to this is that for any change, every element of the view is updated. So, for example, if a person marks a todo item as "done", the text will be re-rendered, possibly losing whatever selection they may have had there. Sometimes that sort of thing is an issue, sometimes it isn't - you'll have to decide based on what exactly your view is doing.

Update only what's changed since the last 'change' event:

This is the more nuanced variation of the above, and combines the best of both approaches. It updates the view elements that need updating based on the changedAttributes() results.

model.bind('change', function() {
  var diff = model.changedAttributes();
  for (var att in diff) {
    switch(att) {
      case 'done':
        view.doneElement.checked = model.get('done');
        break;
      case 'text':
        view.textElement.value = model.get('text');
        break;
      case 'dueDate':
        view.dueDateElement.value = model.get('dueDate');
        break;
    }
  }
});

Finally, I'll note that there's yet another variation on this that involves having the view store a hash of what values it's displaying, and passing that into the changedAttributes() method. That's typically not necessary, so I won't bore you with the details here.

Share:
18,081
fancy
Author by

fancy

Updated on June 08, 2022

Comments

  • fancy
    fancy almost 2 years

    So I'm setting a model with updated attributes.

    Then in my view I'm listening for a change event for this model.

    When that fires I think I should use model.changedAttributes? Do I pass it a callback?

    It should return a hash of all the attributes that are updated, or new? Is there anyway to know which are updated and which are new?

    How should I go about updating once I have this hash of changed attributes? Parse the object to type of attribute or should I just use higher resolution listeners from the get go?

    Thanks!

    • Derick Bailey
      Derick Bailey over 12 years
      @broofa's answer is great. +1 to that... you might also be interested in looking at my ModelBinding plugin for backbone. it can update individual values in the html display, automatically: github.com/derickbailey/backbone.modelbinding
  • fancy
    fancy over 12 years
    as per the backbone docs... changedAttributes: model.changedAttributes([attributes]) Retrieve a hash of only the model's attributes that have changed. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.
  • fancy
    fancy over 12 years
    Thanks for the great answer! How should I approach this? I have a list of items, each item has a few attributes to update. I get an object containing all of these items from the server. I want to take the object of all these items and replace the current set of these objects in the attributes of my model. After that I want to update changed items that exist in the DOM and add items that don't yet exist in the DOM.
  • fancy
    fancy over 12 years
    My first thought was to compare the two objects on my own to determine what is new and what is just updated, what is deleted. I didn't know if backbone helps out here at all.
  • broofa
    broofa over 12 years
    Just do model.set(attributes) - Backbone checks to see if the attributes being set are actually different from what's already in the model (using underscore.js _.isEqual()). So events will only fire if/when an attribute actually changes.
  • fancy
    fancy over 12 years
    How should I figure out if the item is new and needs to be appended to the DOM as opposed to just a updating attributes of an existing item?
  • broofa
    broofa over 12 years
    That's what Backbone.Collection's are for. Model your list using a Collection, and listen to the "add" and "remove" events on the collection.