骨干事件未按预期工作

时间:2014-04-03 21:24:26

标签: javascript backbone.js

我有一个观点

    app.View.FriendRequestButtonView = Backbone.View.extend({

        initialize: function() {
          this.set(a, b, c);
          app.on('foo', this.reject, this);
          app.on('boo', this.accept, this);
    },

    reject: function(){
          this.set(false, false, false);
    },

    accept: function(){
          this.set(true, false, false);
    },

    set: function (a, b, c){
        if(!a && b && c){
            this.events = {
               "click .cancel": "dosomething"
            };
            this.render();
        }
         }
         ........
  } 

当我正常调用视图时,事件"click .cancel": "dosomething"可以正常工作,但当我通过fooboo触发时,事件无效。我做错了什么?

1 个答案:

答案 0 :(得分:1)

视图的events在初始化期间被绑定;以后设置他们不会工作。调用delegateEvents手动绑定它们:

 If an events hash is not passed directly, uses this.events as the source. 

这意味着以下内容应该有效:

this.events = {
    "click .cancel": "dosomething"
};
this.delegateEvents();

this.render();