一 . 新建
var model_1 = new Backbone.Model({‘name‘:‘hello‘});
var model_2 = new Backbone.Model({‘name‘:‘hi‘});
var models = new Backbone.Collection();
models.add( model_1 );
models.add( model_2 );
alert( JSON.stringify(models) );
二. 实例化模型
var M = Backbone.Model.extend({
aaa : function(){
alert(123);
}
});
var ChildM = M.extend();
var model = new ChildM;
model.aaa();
三. 模型上监听事件的方法
$(function(){
var M = Backbone.Model.extend({
defaults : {
name : ‘hello‘
}
});
var V = Backbone.View.extend({
initialize : function(){
this.listenTo( this.model , ‘change‘ , this.show );
},
show : function(model){
$(‘body‘).append( ‘<div>‘+ model.get(‘name‘) +‘</div>‘ );
}
});
var m = new M;
var v = new V({model:m});
m.set(‘name‘,‘hi‘);
});
四. 模型设置和获取后台数据
Backbone.sync = function(method, model) {
alert(method + ": " + JSON.stringify(model));
};
var C = Backbone.Collection.extend({
initialize : function(){
this.on(‘reset‘,function(){
alert(123);
});
},
url: ‘/users‘
});
var models = new C;
models.fetch();
五. 配置理由方法
var Workspace = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/kiwis
"search/:query/p:page": "search" // #search/kiwis/p7
},
help: function() {
alert(1);
},
search: function(query, page) {
alert(2);
}
});
var w = new Workspace;
Backbone.history.start();
六. 视图绑定事件的方法
$(function(){
var V = Backbone.View.extend({
el : $(‘body‘),
events : {
‘click input‘ : ‘aaa‘,
‘mouseover li‘ : ‘bbb‘
},
aaa : function(){
alert(123);
},
bbb : function(){
alert(456);
}
});
var veiw = new V;
});
七. 绑定模型
$(function(){
var M = Backbone.Model.extend({
defaults : {
name : ‘hello‘
}
});
var V = Backbone.View.extend({
initialize : function(){
this.listenTo( this.model , ‘change‘ , this.show );
},
show : function(model){
$(‘body‘).append( this.template(this.model.toJSON()) );
},
template: _.template($(‘#template‘).html())
});
var m = new M;
var v = new V({model:m});
m.set(‘name‘,‘hi‘);
});
八.