Backbone-Nested
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 = name: first: 'Aidan' last: 'Feldman' ; user; userfirst = 'Bob';user;
Wouldn't it be awesome if you could do this?
user;
Installation
Bower
Recommended.
-
Install the latest version:
bower install backbone backbone-nested-model jquery underscore --save -
Add
backbone-nested.js
to your HTML<head>
:<!-- must loaded in this order -->
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 = BackboneModel;// becomesvar Person = BackboneNestedModel; -
Change your getters and setters to not access nested attributes directly, e.g.
userfirst = 'Bob';// becomesuser;
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:
1-1
// dot syntaxuser;user // returns 'Bob'user // returns 'H' // object syntaxuser;
1-N
// object syntaxuser;user // returns 'NY' // square bracket syntaxuser;
Events
"change"
"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;user;user;user; // all of these will fire when the first address is added or changeduser;user;user;user;
"add" and "remove"
Additionally, nested arrays fire "add"
and "remove"
events:
user;user;
Special Methods
add()
Acts like set()
, but appends the item to the nested array. For example:
userlength; //=> 2user;userlength; //=> 3
remove()
Acts like unset()
, but if the unset item is an element in a nested array, the array will be compacted. For example:
userlength; //=> 2user;userlength; //=> 1
See also
Note, this plugin does not handle non-embedded relations (a.k.a. relations), which keeps it relatively simple. If you support for more complex relationships between models, see the Backbone plugin wiki page. There is also an open discussion about merging this project with backbone-deep-model.
Contributing
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):
$ npm install
$ grunt
See also: live tests for latest release.