本文共 1919 字,大约阅读时间需要 6 分钟。
1.视图 1 | var UserView = Backbone.View.extend({ |
2 | initialize: function{/*.......*/}, |
3 | render: function{/*.......*/} |
01 | //每个实例都知道当前的DOM元素或this.el |
02 | //el是由tageName,className,id等属性来创建的元素。 |
04 | var UserView = Backbone.View.extend({ |
09 | assertEqual((new UserView).el.className,"users"); |
11 | //指定el,直接将视图绑定到页面中已存在的元素上 |
12 | var UserView = Backbone.View.extend({ |
16 | //实例化一个试图时传递el,用tageName,className,id等来标记 |
17 | var userView = new UserView({id: "followers"}); |
2.渲染视图 //使用新的HTML来更新el: 01 | var TodoView = Backbone.View.extend({ |
02 | template: _.template($("#todo-template").html()), |
05 | $(this.el).html(this.template(this.model.toJSON())); |
10 | _.template("http://documentcloud.github.com/underscore/#template")是一款生成模版非常方便的工具 |
3.委托事件 //添加事件到el的简单快捷的方法 01 | var TodoView = Backbone.View.extend({ |
03 | "change input[type=checkbox]" : "toggleDone", |
04 | "click .destroy" : "clear", |
07 | toggleDone: function(e){/* ... */}, |
08 | clear: function(e){/* ... */} |
11 | //events对象为{"eventType selector": "callback"},selector可选,如果为空,事件直接绑定在el上 |
4.绑定和上下文 01 | //当模型变化时,会触发change事件,然后调用render重新渲染 |
02 | var TodoView=Backbone.View.extend({ |
03 | initialize: function(){ |
04 | _.bindAll(this, 'render' ,'close'); //_.bindAll (http://documentcloud.github.com/undersocre/#bindAll) |
05 | this.model.bind('change' , this.render); |
08 | close: function(){/* ... */} |
11 | //_.bindAll 保证render()和close()函数总能在TodoView的实例上下文中执行 |
13 | //模型销毁时,删除对应el。视图需要绑定模型的delete事件 |
14 | var TodoView = Backbone.View.extend({ |
15 | initialize: function(){ |
16 | _.bindAll(this, 'render', 'remove'); |
17 | this.model.bind('change', 'this.render'); |
18 | this.model.bind('delete', 'this.remove'); |
转载于:https://my.oschina.net/wbo0801/blog/159708