Book Image

Backbone.js Essentials

By : Jeremy Walker
Book Image

Backbone.js Essentials

By: Jeremy Walker

Overview of this book

<p>This book offers insight into creating and maintaining dynamic Backbone.js web applications. It delves into the the fundamentals of Backbone.js and helps you achieve mastery of the Backbone library.</p> <p>Starting with Models and Collections, you'll learn how to simplify client-side data management and easily transmit data to and from your server. Next, you'll learn to use Views and Routers to facilitate DOM manipulation and URL control so that your visitors can navigate your entire site without ever leaving the first HTML page. Finally, you'll learn how to combine those building blocks with other tools to achieve high-performance, testable, and maintainable web applications.</p>
Table of Contents (20 chapters)
Backbone.js Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Sorting


Backbone can automatically sort all Models added to a Collection if you tell it to by specifying a comparator. As with a model, a Collection's comparator can be provided as an option when the Collection class is created:

var Cats = Backbone.Collection.extend({comparator: 'name'});
var cartoonCats = new Cats();
cartoonCats.comparator; // 'name'

While the provided comparator controls how the Collection sorts its models internally, you can also sort a Collection using alternate comparators by using one of Underscore's sorting methods, which we'll detail at the end of the chapter.

The comparator itself can come in three forms. The first and simplest form is the name of an attribute of the Models in the Collection. If this form is used, Backbone will sort the collection based on the values of the specified attribute:

var cartoonCats = new Backbone.Collection([
    {name: 'Heathcliff'},
    {name: 'Garfield'}
], {
    comparator: 'name'
});
cartoonCats.at(0);// garfield, because his name sorts...