【发布时间】: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