
- attributes
- setting default values
- getting list of attributes
- constructor
- validation
- methods
- converting to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
Additional resources:
No comments:
Post a Comment