此次整理學習View的events和模板相關的內容,事件處理和模板解析都是前端渲染必需的工做,backbone通常把這些內容放到View裏面統一處理。html
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中初始化git
events:聲明格式,'event selector': 'func',這比以前$('.wrapper button#add').on('click', function(){...}); 的方式要清晰許多了。github
在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的聲明中修改:app
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})); ...