[英]Backbone refresh view events
In my view I don't declare this.el because I create it dinamically, but in this way the events don't fire. 在我看来,我没有声明this.el,因为我以恐怖的方式创建它,但是这样事件就不会发生。
This is the code: 这是代码:
View 1: 查看1:
App.Views_1 = Backbone.View.extend({
el: '#content',
initialize: function() {
_.bindAll(this, 'render', 'renderSingle');
},
render: function() {
this.model.each(this.renderSingle);
},
renderSingle: function(model) {
this.tmpView = new App.Views_2({model: model});
$(this.el).append( this.tmpView.render().el );
}
});
View 2: 观点2:
App.Views_2 = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
this.el = $('#template').tmpl(this.model.attributes); // jQuery template
return this;
},
events: {
'click .button' : 'test'
},
test: function() {
alert('Fire');
}
});
});
When I click on ".button" nothing happens. 当我点击“.button”时没有任何反应。 Thanks; 谢谢;
At the end of your render() method, you can tell backbone to rebind events using delegateEvents() . 在render()方法结束时,您可以告诉骨干使用delegateEvents()重新绑定事件。 If you don't pass in any arguments, it will use your events hash. 如果您没有传入任何参数,它将使用您的事件哈希。
render: function() {
this.el = $('#template').tmpl(this.model.attributes); // jQuery template
this.delegateEvents();
return this;
}
As of Backbone.js v0.9.0 (Jan. 30, 2012), there is the setElement method to switching a views element and manages the event delegation. 从Backbone.js v0。9。0(2012年1月30日)开始,有一个setElement方法来切换视图元素并管理事件委托。
render: function() {
this.setElement($('#template').tmpl(this.model.attributes));
return this;
}
Backbone.View setElement : http://backbonejs.org/#View-setElement Backbone.View setElement : http : //backbonejs.org/#View-setElement
setElementview.setElement(element) setElementview.setElement(元件)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one. 如果您想将Backbone视图应用于其他DOM元素,请使用setElement,它还将创建缓存的$ el引用,并将视图的委托事件从旧元素移动到新元素。
Dynamically creating your views in this fashion has it's pros and cons, though: 以这种方式动态创建视图有其优点和缺点:
Pros: 优点:
Cons: - these are mostly negligible 缺点: - 这些几乎可以忽略不计
setElement
will grab the first element from that list and throw away the rest. setElement
将从该列表中获取第一个元素并丢弃其余元素。
setElement
and ensuring that the incoming element.length === 1
. 可以通过解析模板并确保它们解析为单个元素的构建任务,或通过重写setElement
并确保传入的element.length === 1
来缓解此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.