Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it.
How to create a Model in Backbone.
Now lets look at how to create a Model in Backbone
//Create a Model called Cricket
var Cricket=Backbone.Model.extend({
defaults:{
team:'India'
},
initialize:function(){
// trigger when the instance of the model is created
console.log('Model loaded');
}
});
//Create an instance of an Model
var cricket=new Cricket({team:'Australia'});
Now lets take a look at how to set attributes in a model.
Lets take the same Cricket Model
//Create a Model called Cricket
var Cricket=Backbone.Model.extend({
defaults:{
team:'India'
},
initialize:function(){
// trigger when the instance of the model is created
console.log('Model loaded');
}
});
//Create an instance of an Model and setting a value
var cricket=new Cricket({team:'Australia'});
//or you can this way as well. create instance then use set method
var cricket=new Cricket;
cricket.set({team:'Australia'});
Now lets take a look at how to get attributes in a model.
Lets take the same Cricket Model
//Create a Model called Cricket
var Cricket=Backbone.Model.extend({
defaults:{
team:'India'
},
initialize:function(){
// trigger when the instance of the model is created
console.log('Model loaded');
}
});
//Create an instance of an Model and setting a value
var cricket=new Cricket({team:'Australia',playerName:'sachin tendulkar'});
// using get method fetch the values from the model
cricket.get("team") // gets you the team
cricket.get("playerName"); //gets you the player name
How to Manipulate Model attributes in Backbone
//Create a Model called Cricket
var Cricket=Backbone.Model.extend({
defaults:{
team:'India'
},
initialize:function(){
// trigger when the instance of the model is created
console.log('Model loaded');
},
YourMethodName:function(getTeamName){
this.set({team:getTeamName});
}
});
//Create an instance of an Model and setting a value
var cricket=new Cricket({team:'Australia',playerName:'sachin tendulkar'});
cricket.YourMethodName('team India');
// using get method fetch the values from the model
cricket.get("team") // gets you the team India
One Response to getting started with backbone | Models in Backbone
Leave a Reply Cancel reply
Latest posts
- bootstrap popover | bootstrap popover hide on click | bootstrap popover hide on document.click
- Avoid console errors in browsers that lack a console | HTML5 boilerplate
- getting started with Sublime editor | how to install zen coding | zen coding for sublime editor
- getting started with backbone | Models in Backbone
- How to delete a model in backbone







Well I am adding this RSS to my email and can look out for a lot more of your respective fascinating content. Make sure you update this again very soon..