這次整理學習View的events和模板相關的內容,事件處理和模板解析都是前端渲染必需的工作,backbone一般把這些內容放到View裏面統一處理。
2.js
var ListView = Backbone.View.extend({
el: $('.wrapper'),
events: {
'click button#add': 'addItem'
},
// 初始化函數,new時,backbone會自動調用
initialize: function() {
// 用於計數
this.counter = 0;
this.render();
},
// 真正把修改操作同步到瀏覽器中
render: function() {
this.$el.append("<button id='add'>點擊添加</button><ul></ul>");
},
// event handler
addItem: function() {
this.counter++;
this.$('ul').append("<li>Hello techfellow, " + this.counter + " time(s)");
}
});
var listView = new ListView();
執行:
$duo 2.js
知識點
-
this.counter:內部使用的數據,可以initialize中初始化
-
events:聲明格式,'event selector': 'func',這比之前$('.wrapper button#add').on('click', function(){...}); 的方式要清晰許多了。
模板
在index.html中加入:
<script type="text/template" id="tplItem">
<li>Hello techfellow, <%= counter %> time(s)</li>
</script>
<!--要放在2.js前面,否則在執行時,可能遇到找不到tplItem的情況-->
<script src="build/2.js"></script>
在View的聲明中修改:
events: {
'click button#add': 'addItem'
},
template: _.template($('#tplItem').html()),
修改addItem:
addItem: function() {
this.counter++;
this.$('ul').append(this.template({counter: this.counter}));
}
同理,這裏的模板可以替換為任何第三方模板引擎。
比如:artTemplate
var template = require('./lib/template.js');
...
this.$('ul').append(template('tplItem', {counter: this.counter}));
...