2 Model
在Backbone中,Model用于存储核心数据,可以将数据交互相关的逻辑代码放在这里。基本形式如下:
var Human = Backbone.Model.extend({ initialize: function(){ alert("Welcome to this world"); } }); var human = new Human();
设置属性(两种形式)
var human = new Human({ name: "Thomas", age: 67}); // or we can set afterwards, these operations are equivalent var human = new Human(); human.set({ name: "Thomas", age: 67});
获得属性值
var name = human.get("name"); // "Thomas"
设置默认属性(Defaults)
var Human = Backbone.Model.extend({ defaults: { name: 'Fetus', age: 0, child: '' }, initialize: function(){ alert("Welcome to this world"); } });
设置额外的函数修改属性
var Human = Backbone.Model.extend({ defaults: { name: 'Fetus', age: 0, child: '' }, initialize: function(){ alert("Welcome to this world"); }, adopt: function( newChildsName ){ this.set({ child: newChildsName }); } }); var human = new Human({ name: "Thomas", age: 67, child: 'Ryan'}); human.adopt('John Resig'); var child = human.get("child"); // 'John Resig'
监听某个值的变化
var Human = Backbone.Model.extend({ defaults: { name: 'Fetus', age: 0 }, initialize: function(){ alert("Welcome to this world"); this.on("change:name", function(model){ var name = model.get("name"); // 'Stewie Griffin' alert("Changed my name to " + name ); }); } }); var human = new Human({ name: "Thomas", age: 67}); human.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()