Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

Basic usage of models


Models are one of the most important components of Backbone. Starting from storing data, they provide a lot of functionality, including logic around the data, validations, data interactions, and so on. A model can be defined by extending the Backbone.Model class, shown as follows:

var User = Backbone.Model.extend({});

A model consists of an attributes property that stores the data within it. You can get the model data using a get() method and set the data in attributes by using the set() method:

var newUser  =  new User({
  name : 'Jayanti De',     
  age : 40
});

var name = newUser.get('name');  // Jayanti De
newUser.set('age', 42);

console.log(newUser.toJSON()); 
// Output => {"name": "Jayanti De", "age": 42}

The toJSON() method of a model returns a copy of the model attributes as a JSON object. Note that the output has age now set to the new value. Whenever you change any attribute via the set() method, a change event gets fired on the model:

newUser.on('change'...