-
Book Overview & Buying
-
Table Of Contents
Backbone.js Patterns and Best Practices
By :
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'...
Change the font size
Change margin width
Change background colour