Return of Underscore

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

keys

This returns every attribute key

values

This returns every attribute value

pairs

This returns an array of attribute key/value pairs

invert

This returns the attributes with keys and values switched; for instance, an attribute of {'pages': 20} will become {'20': 'pages'}

pick

This returns both the keys and values of only the specified attributes; for instance, book.pick('pages') will return {pages: 20} without any title or other attributes

omit

This returns both the keys and values for every attribute except those specified; for instance, book.omit('pages') will return {title: 'Short Title'}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.233