That covers all the core functionality of Model
, but before we move on to explore Collections
, some of the convenience methods of Model
are worth mentioning. In addition to requiring Underscore, Backbone alo incorporates many Underscore
methods into its classes as shortcut methods, and Model
is a perfect example. The main advantage of using these built-in shortcut methods, besides being a bit more readable, is that they operate on the Model's attributes rather than the Model
itself.
For instance, Underscore has a method called keys
, which you can use to get all the keys on an object. You can use this method directly to get all the keys of a Model's attributes, as follows:
var book = new Backbone.Model({pages: 20, title: 'Short Title'}; var attributeKeys = _.keys(book.attributes); alert(attributeKeys); // alerts ['pages', 'title']
However, if you use Model's version of that same method instead, you can simplify your code slightly and make it slightly more readable:
var attributeKeys = book.keys(); alert(attributeKeys); // alerts ['pages', 'title'];
There are a total of six of these methods on Model
, and while we don't have time to explain all of them in this book, here's a brief summary of what each one does:
Name |
What it does |
---|---|
|
This returns every attribute key |
|
This returns every attribute value |
|
This returns an array of attribute key/value pairs |
|
This returns the attributes with keys and values switched; for instance, an attribute of |
|
This returns both the keys and values of only the specified attributes; for instance, |
|
This returns both the keys and values for every attribute except those specified; for instance, |
3.144.93.141