While the attributes
property is (behind the scenes) just a JavaScript object, that doesn't mean that we should treat it as such. For instance, you should never set an attribute directly by changing the attributes property of a Model
class:
var book = new Book({pages: 200}); book.attributes.pages = 100; // don't do this!
Instead, the attributes of Backbone's Models
should be set using the Model's set
method:
book.set('pages', 100); // do this!
The set
method has two forms or signatures. The first (shown previously) takes two arguments: one for the data's key and one for its value. This form is great if you only want to set one value at a time, but if you need to set multiple values, you can use the second form instead, which takes only a single argument containing all the values of set
:
book.set({pages: 50, currentPage: 49});
In addition, Models also have an unset
method, which takes only a single key argument and works in a similar way as JavaScript's delete
statement, except...