在主干中,如何根据其他事件异步添加事件。我想允许在一组特定的按钮上单击处理程序,但直到单击它们包含的按钮为止。以下是我目前的设置方式:
var ProductsView = Backbone.View.extend({
events : {
"click .filter-options-container" : "filterOptionContainerClick"
},
filterOptionContainerClick: function(e){
$(e.currentTarget).addClass('active');
//want to add an event to all .filter-options to allow them to trigger the filterOptionClick function when clicked
},
filterOptionClick: function(e){
$('.filter-option').removeClass('active');
$(e.currentTarget).addClass('active');
$('.filter-options-container').removeClass('active');
}
});
return ProductsView;
最佳答案
您可以使用另一种方法,而不是在单击容器时为子按钮添加click
处理程序:
- 使用
事件
映射注册一次子按钮的点击
处理程序。 - 向 View 添加 bool 属性以存储容器的状态 点击
- 在
filterOptionContainerClick
处理程序中切换该属性 - 取决于属性的值,允许/禁止点击 子按钮
所以代码应该如下所示:
var ProductsView = Backbone.View.extend({
events : {
"click .filter-options-container" : "filterOptionContainerClick",
"click .filter-options" : "filterOptionClick" // register sub-buttons' click handlers
},
initialize: function() {
this.enabled = false; // state of the container click
},
filterOptionContainerClick: function(e){
this.enabled = !this.enabled;
if (this.enabled) $(e.currentTarget).addClass('active');
else $(e.currentTarget).removeClass('active');
},
filterOptionClick: function(e){
if (!this.enabled) return;
$('.filter-option').removeClass('active');
$(e.currentTarget).addClass('active');
$('.filter-options-container').removeClass('active');
}
});
关于javascript - 在主干中异步添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26532679/