Backbone使用总结
Backbone使用总结
View (主要通过观察者模式)
视图(DOM)通过使用listenTo监听collection,model变化
this.listenTo(c,'remove',function(model, collection){
$('#'+ model.id).remove();
// sum(c.length);
});
this.listenTo(c,'add',function(model, collection){
console.log(model);
console.log(collection);
var view =newView(model);
$("#mail-list").append(view.render().el);
});
视图与视图通信
父视图与子视图之间通信方式:
varParentView=Backbone.View.extend({
tagName:'div',
id:'parentDiv',
initialize:function(){
this.childView =newChildView();
},
render:function(){
this.$el.html(this.childView.render().el);
returnthis;
}
});
varChildView=Backbone.View.extend({
tagName:'div',
id:'childDiv',
render:function(){
this.$el.html('hello wrold');
returnthis;
}
});
var parentView =newParentView();
$('body').append(parentView.render().el);
子视图与子视图之间通信方式:
方式一:通过父视图
varParentView=Backbone.View.extend({
tagName:'div',
id:'parentDiv',
initialize:function(){
this.childView =newChildView();
this.childView2 =newChildView2();
//方式一
this.childView.listenTo(this.childView2,'test',function(data){
console.log('--------------');
console.log('data--->',data);
});
},
render:function(){
this.$el.html(this.childView.render().el);
this.$el.append(this.childView2.render().el);
console.log('trigger childrenView2');
this.childView2.trigger('test');
returnthis;
}
});
varChildView=Backbone.View.extend({
tagName:'div',
id:'childDiv',
render:function(){
this.$el.html('hello wrold');
returnthis;
}
});
varChildView2=Backbone.View.extend({
tagName:'div',
id:'childDiv2',
initialize:function(){
this.on('test',function(){
console.log('hello');
});
},
render:function(){
this.$el.html('hello wrold222222222');
returnthis;
}
});
var parentView =newParentView();
$('body').append(parentView.render().el);
方式二:通过全局便利Backbone
varParentView=Backbone.View.extend({
tagName:'div',
id:'parentDiv',
initialize:function(){
this.childView =newChildView();
this.childView2 =newChildView2();
},
render:function(){
this.$el.html(this.childView.render().el);
this.$el.append(this.childView2.render().el);
returnthis;
}
});
varChildView=Backbone.View.extend({
tagName:'div',
id:'childDiv',
render:function(){
Backboone.trigger('children2',{name:'children111111111111111'});
this.$el.html('hello wrold');
returnthis;
}
});
varChildView2=Backbone.View.extend({
tagName:'div',
id:'childDiv2',
initialize:function(){
Backbone.on('children2',function(data){
console.log('this is ChilrenView2222222222222');
console.log(data);//{name:'children111111111111111'}
})
},
render:function(){
this.$el.html('hello wrold222222222');
returnthis;
}
});
var parentView =newParentView();
$('body').append(parentView.render().el);
* 数据逻辑处理尽量不要放在视图层(View)
未完。。。。。。。。。。。。。。。。