Skip to content

Instantly share code, notes, and snippets.

@papsl
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save papsl/11446627 to your computer and use it in GitHub Desktop.
Save papsl/11446627 to your computer and use it in GitHub Desktop.
Backbone Tutorials - Model
Person = Backbone.Model.extend({
// default values of attributes
defaults:{
age:0,
children: []
},
// validation
validate: function(attributes){
if(attributes.age<0){
console.log("Validation error, person can't be negative age!");
return "person can't be negative age";
}
},
// constructor method
initialize: function(){
console.log("New person was born");
this.bind("error",function(model,error){
console.log("ERROR:"+model);
});
// Listen to attribute changes (using bind)
this.bind("change:name", function(){
var currentName=this.get("name");
console.log("Name changed from "+currentName + " to " + name);
});
},
// custom methods
adopt: function(newChildsName){
var childrenArraya=this.get("children");
childrenArraya.push(newChildsName);
this.set({"children": childrenArraya});
},
replaceNameAttr: function(name){
this.set({name: name});
}
});
var person = new Person();
person.set({name: "John", lastName:"Dove", children: ["First","Second"]});
person.adopt("Tara");
// validation is only run on save method or by turning on validate option on set method (since Backbone 0.9.10)
person.set("age", -5 , {validate : true});
this.person.save({age: -10});
console.log("Hi, "+person.get("name")+" and "+person.get("children"));
person.replaceNameAttr("Johny");
// person.set({name: "Milan"});
// convert to JSON
console.log(person.toJSON());
// show all attributes
console.log(person.attributes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment