var UserView = Backbone.View.extend({
initialize: function{/*.......*/},
render: function{/*.......*/}
});
//每个实例都知道当前的DOM元素或this.el
//el是由tageName,className,id等属性来创建的元素。
//如果没指定这些值,el是一个空div
var UserView = Backbone.View.extend({
tagName: "span",
className: "users"
});
assertEqual((new UserView).el.className,"users");
//指定el,直接将视图绑定到页面中已存在的元素上
var UserView = Backbone.View.extend({
el: $(".users")
});
//实例化一个试图时传递el,用tageName,className,id等来标记
var userView = new UserView({id: "followers"});
2.渲染视图 //使用新的HTML来更新el:
var TodoView = Backbone.View.extend({
template: _.template($("#todo-template").html()),
render: function(){
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
})
_.template("http://documentcloud.github.com/underscore/#template")是一款生成模版非常方便的工具
3.委托事件 //添加事件到el的简单快捷的方法
var TodoView = Backbone.View.extend({
events: {
"change input[type=checkbox]" : "toggleDone",
"click .destroy" : "clear",
},
toggleDone: function(e){/* ... */},
clear: function(e){/* ... */}
});
//events对象为{"eventType selector": "callback"},selector可选,如果为空,事件直接绑定在el上
4.绑定和上下文
//当模型变化时,会触发change事件,然后调用render重新渲染
var TodoView=Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render' ,'close'); //_.bindAll (http://documentcloud.github.com/undersocre/#bindAll)
this.model.bind('change' , this.render);
},
close: function(){/* ... */}
});
//_.bindAll 保证render()和close()函数总能在TodoView的实例上下文中执行
//模型销毁时,删除对应el。视图需要绑定模型的delete事件
var TodoView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render', 'remove');
this.model.bind('change', 'this.render');
this.model.bind('delete', 'this.remove');
},
remove: function(){
$(this.el).remove();
}
});