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

  1. 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..

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get all fix get all the fixes for CSS, Jquery and any web2.0 related queries
Set your Twitter account name in your settings to use the TwitterBar Section.