这种方式来绑定这个在Ember中的稍后调用
问题描述:
只是想知道如何处理“稍后调用”,当需要在外部作用域中引用“this”时。根据idomatic.js,Aliase似乎不是很好的做法。我引述:这种方式来绑定这个在Ember中的稍后调用
超越呼叫一般是众所周知的使用情况和应用, 总是喜欢.bind(本)或同等功效,用于创建以后调用 BoundFunction定义。当没有可用的选项时,只能使用 别名。
那么在Ember中有没有自以为是的方式?例如:
export default Ember.Route.extend({
model() {
return new Ember.RSVP.Promise(function(resolve) {
Ember.run.later(function() {
resolve({ msg: 'Hold Your Horses' });
}, 3000);
});
},
setupController(controller, model) {
console.log(model.msg); // "Hold Your Horses"
}
});
如果在Ember.run.later()
我想this
解决后做一些事情:
this.controllerFor("application").set("dataReady", true);
例如。
我想,用aliase that
是:
model() {
let that = this;
return new Ember.RSVP.Promise(function(resolve) {
Ember.run.later(function() {
that.controllerFor('application').set('dataReady', true);
resolve({ msg: 'Hold Your Horses' });
}, 3000);
});
},
但有什么更好的办法?
答
除了使用别名,您可以使用arrow functions来维护范围。沿着这些线路的东西应该工作:
model() {
return new Ember.RSVP.Promise((resolve) => {
Ember.run.later(this, function() {
this.controllerFor('application').set('dataReady', true);
resolve({ msg: 'Hold Your Horses' });
}, 3000);
});
},
注意,传递给Ember.run.later
回调并不需要是一个箭头的功能,因为你可以pass an object as the first argument of Ember.run.later
到的环境中使用。
+0
Ember是否提供浏览器支持箭头功能?该链接表示,Safari和IE不支持箭头功能。 – Hao
那么,为什么不使用bind(this)呢? –
没有原因。只是想知道Ember是否有自己的方式。 – Hao