Basic usage of collections
We will start looking into different features of the Backbone
collection with a simple example. Let's assume we have a User
model and a Users
collection.
// Model definition var User = Backbone.Model.extend({ initialize: function () { this.on('change', function () { console.log('User model changed!'); }); } }); // Collection definition var Users = Backbone.Collection.extend({ model: User, url : '/users', initialize: function () { this.on('change', function () { console.log('Users collection changed!'); }); } }); var users = new Users(), newUser = new User({ name: 'Jayashi De', age: 21 }); users.add([newUser]); // Change an attribute of the model newUser.set('age', 22);
In the preceding code, simple model and collection definitions have been described. Here, we tried to demonstrate, as we mentioned in the introduction of this chapter, that any event fired on a model will get fired on the collection too. When...