A plugin to make Backbone.js keep track of nested attributes. Download the latest version and see the changelog/history/release notes on the Releases page. Supports Backbone 0.9.x and 1.x.
The Need
Suppose you have a Backbone Model with nested attributes, perhaps to remain consistent with your document-oriented database. Updating the nested attribute won't cause the model's "change" event to fire, which is confusing.
var user = new Backbone.Model({ name: { first: 'Aidan', last: 'Feldman' }});user.bind('change', function(){ // this is never reached!});user.get('name').first = 'Bob';user.save();
<!-- must loaded in this order --><script type="text/javascript" src="/bower_components/jquery/jquery.js"></script><script type="text/javascript" src="/bower_components/underscore/underscore.js"></script><script type="text/javascript" src="/bower_components/backbone/backbone.js"></script><script type=
Manual
Download the latest release and the dependencies listed above, then include with script tags in your HTML.
Usage
Change your models to extend from Backbone.NestedModel, e.g.
var Person = Backbone.Model.extend({ ... });// becomesvar Person = Backbone.NestedModel.extend({ ... });
Change your getters and setters to not access nested attributes directly, e.g.
Best of all, Backbone.NestedModel is designed to be a backwards-compatible, drop-in replacement of Backbone.Model, so the switch can be made painlessly.
Nested Attributes
get() and set() will work as before, but nested attributes should be accessed using the Backbone-Nested string syntax:
"change" events can be bound to nested attributes in the same way, and changing nested attributes will fire up the chain:
// all of these will fire when 'name.middle.initial' is set or changeduser.bind('change', function(model, newVal){ ... });user.bind('change:name', function(model, newName){ ... });user.bind('change:name.middle', function(model, newMiddleName){ ... });user.bind('change:name.middle.initial', function(model, newInitial){ ... });// all of these will fire when the first address is added or changeduser.bind('change', function(model, newVal){ ... });user.bind('change:addresses', function(model, addrs){ ... });user.
"add" and "remove"
Additionally, nested arrays fire "add" and "remove" events:
Pull requests are more than welcome - please add tests, which can be run by opening test/index.html. They can also be run from the command-line (requires PhantomJS):