在主干中异步添加事件

Asynchronously add events in backbone

本文关键字:添加 事件 异步      更新时间:2023-09-26

在主干网中,如何根据其他事件异步添加事件。我想允许对一组特定的按钮进行单击处理程序,但在单击它们的包含按钮之前不能。以下是我目前设置的内容:

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. 使用地图注册一次子按钮的click处理程序events
  2. 将布尔属性添加到视图以存储容器的状态点击
  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');
    }
});