Introduction
This article explains Models in Backbone.JS. Backbone.JS is a JavaScript framework for creating web applications. It is gaining in popularity in the web application community among the other frameworks. It uses the structure given by JavaScript.
Backbone follows the pattern MV* (Model View). In other words, the model contains the interactive data and logic of this data. We use a model in Backbone to represent the concept of the object using its attributes. The view of the Backbone not only works as a view but also works as a controller for connecting the model to the data interaction.
There is a different concept in Backbone in which one is the Model. So now we learn about the Model in Backbone.
Model
A Model in Backbone consists of the connected data for the web application. It also contains the connection among the data. We use the models for representing the concept of the object including its attribute. When we create a model it's extended from the "Backbone.Model".
Here we provide sample code for creating the Model. We use a Model representing an image object such as title, location (src) and so on.
var Photo = Backbone.Model.extend({
defaults: {
src: 'placeholder.jpg',
title: 'Image',
coordinates: [0, 0]
},
initialize: function () {
this.on("change:src", function () {
var src = this.get("src");
console.log('Source ' + src);
});
},
changeSrc: function (source) {
this.set({ src: source });
}
});
var somePhoto = new Photo({ src: "Koala.jpg", title: "Pic" });
somePhoto.changeSrc("Desert.jpg"); // which triggers "change:src" and logs an update message to the console.
Attributes of the Model. There are various types of attribute accessing methods that are used by the Model.
- Model.get()
- Modet.set()
- Default Values
- Validation
Model.get():
Model.get() provides an easy way to access the attributes. The attributes passed to the model at the time of instantiation that are ready to be fetched.
var Image = new Photo({
title: "This is pic",
src: "Desert.jpg",
location: "esert",
tags: ['the big game', 'vacation']
}),
title = Image.get("title"), //This is pic
location = Image.get("location"), //Desert
tags = Image.get("tags"), // ['the big game','vacation']
photoSrc = Image.get("src"); //Desert.jpg

Join the conversation! Your thoughts help the community grow.