在骨干网中异步添加事件

时间:2014-10-23 16:20:28

标签: javascript backbone.js asynchronous javascript-events backbone-events

在骨干网中,如何基于其他事件异步添加事件。我想在某组按钮上允许点击处理程序,但是在点击其包含按钮之前不允许。以下是我目前设置的方法:

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;

1 个答案:

答案 0 :(得分:1)

不管在单击容器时为子按钮添加click处理程序,您都可以使用其他方法:

  1. 使用click地图注册子按钮'events处理程序一次。
  2. 将boolean属性添加到View以存储容器的状态 点击
  3. filterOptionContainerClick处理程序
  4. 中切换该属性
  5. 取决于属性的值,允许/禁止单击 子按钮
  6. 所以代码应如下所示:

    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');
        }
    
    });