【问题标题】:Ember.js: this._super in a callback functionEmber.js:回调函数中的 this._super
【发布时间】:2014-07-31 10:06:50
【问题描述】:

我试图弄清楚当从回调中调用 Ember 的对象方法时如何使用 this._super。

我知道我可以在调用回调之前分配var _super = this._super,但我不喜欢它。

我希望 this 对象在回调中包含正确的 _super 方法。

我的代码在这里:http://emberjs.jsbin.com/hasehija/6/edit。

App.BaseMixin = Ember.Mixin.create({
  init: function() {
    console.log("base");
  }
});

App.Utils = Ember.Object.extend({
  callbackMethod: function(callback, ctx) {
    // asynchronous callback
    Ember.run(function() {
      callback.call(ctx);
    });
  }
});

App.MyObject = Ember.Object.extend(App.BaseMixin, {
  init: function() {
    console.log("MyObject");
    var _super = this._super;
    App.Utils.create().callbackMethod(function() {
      this._super(); // this._super is undefined here
      // _super() would work
    }, this);
  }
});

App.ApplicationController = Ember.Controller.extend({
  init: function() {
    new App.MyObject();
  }
});

你知道有什么办法可以解决吗?


更新:

原来它已在 Ember 1.5.0 中修复(@GJK:谢谢你的回答),而我使用的是 Ember 1.4.0。

【问题讨论】:

  • 在您的 jsbin 中,我只收到一个错误,即 App.Utils.callbackMethod 未定义,而不是 this._super 不起作用?
  • 是的,我也知道您的代码不起作用...因为回调方法是实例方法而不是静态方法,所以您需要创建一个实例。无论如何,为什么不在 init 方法的顶部使用var self = this 创建对this 的引用。然后,您仍然可以访问该对象上的所有内容,而不仅仅是超级函数。
  • 需要注意的是,如果你打算异步调用this._super(),它是行不通的。 Ember 1.5.0 改变了这一点。
  • 老实说,建议你不要覆盖init,如果你想在init上做一些事情你应该创建一个方法,然后加上on('init')(下面添加示例)

标签: javascript ember.js callback super


【解决方案1】:

extend 定义一个类

App.Utils = Ember.Object.extend({
  callbackMethod: function(callback, ctx) {
    callback.call(ctx);
  }
});

create 构建类的实例

App.Utils = Ember.Object.create({
  callbackMethod: function(callback, ctx) {
    callback.call(ctx);
  }
});

或

App.Utils.create().callbackMethod(function() {
  this._super(); 
}, this);

http://emberjs.jsbin.com/hasehija/7/edit

或者避免覆盖init

App.ApplicationController = Ember.Controller.extend({
  doSomething: function() {
    new App.MyObject();
  }.on('init')
});

【讨论】:

  • 嗨,谢谢。显然我在提供的代码中犯了一个错误。我可以选择App.Utils.create() 或new App.Utils(),但这不是重点。正如@GJK 提到的那样,这个问题似乎在 Ember 1.5.0 中得到了解决。
  • 我不明白,1.5 是一个重大更改,它不会解决您描述的问题。你从来没有异步回拨过。
  • 是的,你显然是对的。在所示示例中,我使用了同步回调。在实际项目中,我有一个异步回调。我不知道这是它背后的真正原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 2012-03-15
  • 2016-07-20
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 2017-04-22
相关资源
最近更新 更多