gpt4 book ai didi

javascript - 在主干中异步添加事件

转载 作者:行者123 更新时间:2023-12-03 11:35:29 25 4
gpt4 key购买 nike

在主干中,如何根据其他事件异步添加事件。我想允许在一组特定的按钮上单击处理程序,但直到单击它们包含的按钮为止。以下是我目前的设置方式:

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处理程序:

  1. 使用事件映射注册一次子按钮的点击处理程序。
  2. 向 View 添加 bool 属性以存储容器的状态点击
  3. filterOptionContainerClick 处理程序中切换该属性
  4. 取决于属性的值,允许/禁止点击子按钮

所以代码应该如下所示:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com