backbone.js初始化侦听器与事件

时间:2013-10-02 23:08:20

标签: events backbone.js views listener

我不明白在视图内的初始化函数中放置“click”侦听器并将其放在同一视图中的events对象之间的区别。他们都监听DOM事件和触发函数,对吧?有什么区别?

例如:

var ViewName = Backbone.View.extend({  
    initialize: function(){  
        this.$el.on("eventName", this.functionName, this)  
    },  
    functionName: function(){  
        //whatever  
    }  
});

var ViewName = Backbone.View.extend({  
    events: { "eventName": "fucntionName" }   
    },  
    functionName: function(){  
        //whatever  
    }  
});

1 个答案:

答案 0 :(得分:12)

当你这样做时:

var ViewName = Backbone.View.extend({  
   initialize: function(){  
      this.$el.on("eventName", this.functionName, this)  
   },  
   functionName: function(){  
    //whatever  
   }  
});

删除视图时,您必须手动取消绑定事件。所以,你必须做类似的事情:

var ViewName = Backbone.View.extend({  
   initialize: function(){  
      this.$el.on("eventName", this.functionName, this)  
   },  
   functionName: function(){  
    //whatever  
   },
   remove: function() {
      this.$el.off("eventName", this.functionName);
      Backbone.View.prototype.remove.apply(this, arguments);
   }  
});

如果您使用events哈希,Backbone会在删除视图时处理取消分配事件。这一切都在this section of the Backbone.js annotated source中解释。