我有一个点击处理程序,需要一个接一个地进行多个异步调用。我选择使用承诺来构建这些调用(RSVP https://github.com/tildeio/rsvp.js,准确地说)。
下面,您可以看到clickA
处理程序,在控制器内部(这是一个 Ember 应用程序,但我认为问题更普遍):
App.SomeController = Ember.Controller.extend({
actions: {
clickA: function() {
var self = this;
function startProcess() {
return makeAjaxCall(url, {
'foo': self.get('foo')
});
}
function continueProcess(response) {
return makeAjaxCall(url, {
'bar': self.get('bar')
});
}
function finishProcess(response) {
return new Ember.RSVP.Promise(...);
}
...
startProcess()
.then(continueProcess)
.then(finishProcess)
.catch(errorHandler);
}
}
});
它看起来很棒,但现在我必须添加第二个操作来重用某些步骤。
由于每个内部函数都需要访问控制器的属性,一种解决方案是将它们设为控制器的方法:
App.SomeController = Ember.Controller.extend({
startProcess: function() {
return makeAjaxCall(url, {
'foo': this.get('foo')
});
},
continueProcess: function(response) {
return makeAjaxCall(url, {
'bar': this.get('bar')
});
},
finishProcess: function(response) {
return new Ember.RSVP.Promise(...);
},
actions: {
clickA: function() {
this.startProcess()
.then(jQuery.proxy(this, 'continueProcess'))
.then(jQuery.proxy(this, 'finishProcess'))
.catch(jQuery.proxy(this, 'errorHandler'));
},
clickB: function() {
this.startProcess()
.then(jQuery.proxy(this, 'doSomethingElse'))
.catch(jQuery.proxy(this, 'errorHandler'));
}
}
});
所以,我的问题是:有更好的方法吗?我可以摆脱所有这些吗jQuery.proxy()
以某种方式打电话?