【问题标题】:How to get the right class context from a method when it is invoked from a callback从回调调用方法时如何从方法中获取正确的类上下文
【发布时间】:2013-02-18 14:54:59
【问题描述】:

我使用Class.js 来创建类。

从回调函数调用时,我没有在方法中获得正确的上下文

我的代码是

WordCloud = MyClass.extend({
    init: function(data) {
        var me = this;
        (......).on("onComplete", this.draw);
    },
    show: function(word) {
        alert(word)
    },
    draw : function(words){
        console.debug(this); // prints element that triggred `onComplete` action
        console.debug(words); // "Hi"
        console.debug(me); // me is not defined
        me.show(words) // Need to call this method
    }
});

问题是draw方法在动作完成时被触发,但在draw方法内部this不是实际的class实例,而是触发回调动作的元素。

在调用this.draw 时我无法传递额外参数,因为它是一个回调函数,而onComplete 只有一个参数。

如何从draw 调用show 方法?

【问题讨论】:

    标签: javascript oop class callback


    【解决方案1】:

    如果您不必支持 Internet Explorer 8 或更低版本,可以使用bind()

    init: function(data) {
        var me = this;
        (......).on("onComplete", this.draw.bind(this));
    }
    

    否则,如果您已经在使用 jQuery,则可以利用 $.proxy(),其工作方式相同:

    init: function(data) {
        var me = this;
        (......).on("onComplete", $.proxy(this.draw, this));
    }
    

    【讨论】:

      【解决方案2】:

      我在这些情况下使用辅助函数。

      function hitch(obj, func) {
          return function() {
              return obj[func].apply(obj, arguments || [])
          };
      }
      

      要调用它,您可以使用 hitch(this, 'draw'); 而不是 this.draw

      或者为了更简单,您可以在基类中添加一个简化版本

      function hitch(func) {
          var that = this;
          return function() {
              return that[func].apply(that, arguments || [])
          };
      }
      

      只需致电this.hitch('draw');

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-25
        • 2019-12-09
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多