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

Collections and Models


Every Collection class has a model property, which defaults to Backbone.Model. You can set this property by providing it as an option when you use extend to create your Collection subclass:

var Cats = Backbone.Collection.extend({model: Cat});
var cats = new Cats(); // cats.model == Cat

However, this model property doesn't actually limit the type of Model a Collection can hold, and in fact, any Collection can hold any type of Model:

var Cat = Backbone.Model.extend();
var Cats = Backbone.Collection.extend({model: Cat});
var Dog = Backbone.Model.extend();
var snoopy = new Dog({name: 'Snoopy'});
var cartoonCats = new Cats([snoopy]);
cartoonCats.models[0] instanceof Dog; // true

This is because the model property of a Collection is only used when new Models are created through the Collection. One way in which this can happen is when the Collection is initialized with an array of attributes, as shown in the following example:

var snoopyAttributes = {id: 'dog1', name: 'Snoopy...