主要成分:事件失去了重新渲染 [英] Backbone: event lost in re-render
问题描述
我的超级视图的谁负责渲染的子观的。当我的重新渲染的的的超级视图的在子视图中的所有事件的丢失。
I have super-View who is in charge of rendering sub-Views. When I re-render the super-View all the events in the sub-Views are lost.
这是一个例子:
var SubView = Backbone.View.extend({
events: {
"click": "click"
},
click: function(){
console.log( "click!" );
},
render: function(){
this.$el.html( "click me" );
return this;
}
});
var Composer = Backbone.View.extend({
initialize: function(){
this.subView = new SubView();
},
render: function(){
this.$el.html( this.subView.render().el );
}
});
var composer = new Composer({el: $('#composer')});
composer.render();
当我点击的点击我的DIV事件被触发。如果我执行 composer.render()
再次一切看起来pretty相同的,但的点击事件的不会被触发了。
When I click in the click me div the event is triggered. If I execute composer.render()
again everything looks pretty the same but the click event is not triggered any more.
检查工作的jsfiddle 。
推荐答案
当你这样做:
this.$el.html( this.subView.render().el );
您正在有效地这样说:
this.$el.empty();
this.$el.append( this.subView.render().el );
和 空
杀死里面的<$ C上的一切事件。$ C>这$埃尔:
要避免内存泄漏,jQuery的删除元素本身之前将其他结构如子元素的数据和事件处理程序。
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
所以,你失去了代表
电话结合的 this.subView
事件和子视图渲染#
不会重新绑定他们。
So you lose the delegate
call that binds events on this.subView
and the SubView#render
won't rebind them.
您需要滑 this.subView.delegateEvents()
调入这一点。$ el.html()
但你需要它的空()
。你可以做这样的:
You need to slip a this.subView.delegateEvents()
call into this.$el.html()
but you need it to happen after the empty()
. You could do it like this:
render: function(){
console.log( "Composer.render" );
this.$el.empty();
this.subView.delegateEvents();
this.$el.append( this.subView.render().el );
return this;
}
演示: http://jsfiddle.net/ambiguous/57maA/1/
或者是这样的:
render: function(){
console.log( "Composer.render" );
this.$el.html( this.subView.render().el );
this.subView.delegateEvents();
return this;
}
演示: http://jsfiddle.net/ambiguous/4qrRa/
或者你可以 删除
并重新创建 this.subView
渲染时和回避问题的方式(但可能会导致其他问题...)。
Or you could remove
and re-create the this.subView
when rendering and sidestep the problem that way (but this might cause other problems...).
这篇关于主要成分:事件失去了重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!