Giter VIP home page Giter VIP logo

backbone-nested's Introduction

Backbone-Nested Build Status

A plugin to make Backbone.js keep track of nested attributes. Download minified version.

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();

Wouldn't it be awesome if you could do this?

user.bind('change:name.first', function(){ ... });

Usage

  1. Download the latest version here, and add backbone-nested.js to your HTML <head>, after backbone.js is included (tested against jQuery v1.7.2, Underscore v1.3.3 and Backbone v0.9.2).

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="backbone.js"></script>
    <script type="text/javascript" src="backbone-nested.js"></script>
  2. Change your models to extend from Backbone.NestedModel, e.g.

    var Person = Backbone.Model.extend({ ... });
    
    // becomes
    
    var Person = Backbone.NestedModel.extend({ ... });
  3. Change your getters and setters to not access nested attributes directly, e.g.

    user.get('name').first = 'Bob';
    
    // becomes
    
    user.set({'name.first': 'Bob'});

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 syntax
user.set({
  'name.first': 'Bob',
  'name.middle.initial': 'H'
});
user.get('name.first') // returns 'Bob'
user.get('name.middle.initial') // returns 'H'

// object syntax
user.set({
  'name': {
    first: 'Barack',
    last: 'Obama'
  }
});

1-N

// object syntax
user.set({
  'addresses': [
    {city: 'Brooklyn', state: 'NY'},
    {city: 'Oak Park', state: 'IL'}
  ]
});
user.get('addresses[0].state') // returns 'NY'

// square bracket syntax
user.set({
  'addresses[1].state': 'MI'
});

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 changed
user.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 changed
user.bind('change', function(model, newVal){ ... });
user.bind('change:addresses', function(model, addrs){ ... });
user.bind('change:addresses[0]', function(model, newAddr){ ... });
user.bind('change:addresses[0].city', function(model, newCity){ ... });

"add" and "remove"

Additionally, nested arrays fire "add" and "remove" events:

user.bind('add:addresses', function(model, newAddr){ ... });
user.bind('remove:addresses', function(model, oldAddr){ ... });

Special Methods

add()

Acts like set(), but appends the item to the nested array. For example:

user.get('addresses').length; //=> 2
user.add('addresses', {
  city: 'Seattle',
  state: 'WA'
});
user.get('addresses').length; //=> 3

remove()

Acts like unset(), but if the unset item is an element in a nested array, the array will be compacted. For example:

user.get('addresses').length; //=> 2
user.remove('addresses[0]');
user.get('addresses').length; //=> 1

Changelog

HEAD (diff)

  • fix remove() not firing 'remove' event when last element of array is removed (thanks @Kmandr)
  • fix clear() and set nested attributes on changedAttributes() (thanks @isakb)
  • 'change' events will no longer fire if new value matches the old

1.1.2 (diff)

  • changedAttributes() should include the nested attribute paths
  • remove warnings when retrieving nested objects - more of a nuisance than a convenience

1.1.1 (diff)

  • fixed remove() to not insert array back into itself
  • upgraded test suite to Backbone 0.9.2

1.1.0 (diff)

  • Backbone 0.9.1 compatibiity
  • fire 'remove' event from remove()
  • added add() method
  • added demo pages

1.0.3 (diff)

1.0.2 (diff)

  • added option to silence get() warnings for non-leaf attributes

1.0.1 (diff)

  • header and documentation fixes

1.0.0

Initial release!

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

backbone-nested's People

Contributors

afeld avatar gerhobbelt avatar isakb avatar michaelcox avatar p3drosola avatar trevorquinn avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.