View的学习
本章会通过一个简单的搜索框的demo,学习View模块和View的事件属性
在线demo:
搜索框demo
前面我们已经知道
initialize()方法会在实例化Model时执行,而View和Collection也有对应的方法,所以我们可以在此方法里定义一些动作。如:
var App = Backbone.View.extend({
initialize: function() {
alert('hello');
},
});
var app = new App();
template
在页面定义模板,然后利用jquery的html()方法获取和underscore的template方法转义
<script type="text/template" id="search_template">
<label><%= search_label %></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
以<script>标签定义了模板,而浏览器不认识type="text/template"所以会被忽略,但我们可以通过对应id来获取模板
el属性
所有视图都拥有一个DOM元素(el属性)。el可以从视图的tagName, className, id, attribute以及jquery对象创建,如果为指定,el会是一个空div
var App = Backbone.View.extend({
// 定义el
el: $("#search_container"),
initialize: function() {
this.render();
},
render: function() {
var label = {
search_label: '搜索框'
};
// 先用html()方法获取对应的模板
// 再用template方法编译
var template = _.template($("#search_template").html());
// 传入对应的参数
this.$el.html(template(label));
},
});
这样就能完成模板的获取,变量的填充,最后加载编译后的模板到对应的el中
监听事件
在View类中定义events属性能
监听el及其子元素上的事件
var App = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var label = {
search_label: '搜索框'
};
var template = _.template($("#search_template").html());
this.$el.html(template(label));
},
events: {
// 以'[事件类型] [事件元素]':'事件处理程序'来定义事件
'click #search_button': 'doSearch'
},
doSearch: function(e) {
// this指向容器el,而不是事件的目标元素!因为虽然函数时View的方法,但是调用的时候是作为元素的方法被调用!
// 所以要通过e.srcElement || e.target?来获取当前目标?
var $el = $(e.srcElement || e.target);
alert('你正在搜索:' + $("#search_input").val());
}
});
var app = new App({
el: $("#search_container")
});
在events属性上定义事件类型(click)和对应的事件元素(#search_button),再指定事件的处理程序(doSearch),完成事件的绑定