Javascript MVC框架Backbone.js详解(2)
var Document = Backbone.View.extend({
tagName: "li",
className: "document",
render: function() {
// ...
}
});
template方法
视图的template属性用来指定网页模板。
var AppView = Backbone.View.extend({
template: _.template("<h3>Hello <%= who %><h3>"),
});
上面代码中,underscore函数库的template函数,接受一个模板字符串作为参数,返回对应的模板函数。有了这个模板函数,只要提供具体的值,就能生成网页代码。
var AppView = Backbone.View.extend({
el: $('#container'),
template: _.template("<h3>Hello <%= who %><h3>"),
initialize: function(){
this.render();
},
render: function(){
this.$el.html(this.template({who: 'world!'}));
}
});
上面代码的render就调用了template方法,从而生成具体的网页代码。
实际应用中,一般将模板放在script标签中,为了防止浏览器按照JavaScript代码解析,type属性设为text/template。
<script type="text/template" data-name="templateName">
<!-- template contents goes here -->
</script>
可以使用下面的代码编译模板。
window.templates = {};
var $sources = $('script[type="text/template"]');
$sources.each(function(index, el) {
var $el = $(el);
templates[$el.data('name')] = _.template($el.html());
});
events属性
events属性用于指定视图的事件及其对应的处理函数。
var Document = Backbone.View.extend({
events: {
"click .icon": "open",
"click .button.edit": "openEditDialog",
"click .button.delete": "destroy"
}
});
上面代码中一个指定了三个CSS选择器的单击事件,及其对应的三个处理函数。
listento方法
listento方法用于为特定事件指定回调函数。
var Document = Backbone.View.extend({
initialize: function() {
this.listenTo(this.model, "change", this.render);
}
});
上面代码为model的change事件,指定了回调函数为render。
remove方法
remove方法用于移除一个视图。
updateView: function() {
view.remove();
view.render();
};
子视图(subview)
在父视图中可以调用子视图。下面就是一种写法。
render : function (){
this.$el.html(this.template());
this.child = new Child();
this.child.appendTo($.('.container-placeholder').render();
}
Backbone.Router
Router是Backbone提供的路由对象,用来将用户请求的网址与后端的处理函数一一对应。