问题描述
我有一个组件需要与一个控制器进行通信,最后执行一些清理 控制器说一切都OK(即jQueryun初始化)。我认为完成这一工作的最好方法是承诺,以便组件可以在控制器完成任务之后进行清理。但控制器行动如何能够回报承诺?或者,组件可以直接在控制器上调用动态方法?
I have a component that needs to communicate with a controller and eventually perform some clean up after the controller says everything is ok (ie, jQuery "un"-initialization). I think the best way to accomplish this is with a promise so that the component can clean up after the controller completes its task. But how can a controller action return a promise? Alternatively, can a component call a dynamic method directly on a controller?
例如,让我说我有一个 ModalDialogComponent
。
For example, lets say I have a ModalDialogComponent
.
App.ModalDialogComponent = Ember.Component.extend
didInsertElement: ->
@$('.modal').modal('show')
actions:
save: ->
@sendAction('save').then(@closeModal.bind(@))
# some other actions are omitted
closeModal: ->
@$('.modal').modal('hide')
而且可以在名为 foo
的模板中实例化组件,
And I can instantiate the component inside a template named foo
,
{{modal-form save="save" ...}}
并实现在FooController上保存
方法
App.FooController = Ember.ObjectController.extend
save: ->
# how can we tell the component that this was successful?
如您所见,我只想要 closeModal 保存
操作成功,则执行c>函数。换句话说,只有在记录保存成功的情况下才关闭模式。
As you can see, I only want the closeModal
function to execute if the save
action was successful. In other words, only close the modal if the record was saved successfully.
这是可能的,还是我完全错了?
Is this possible, or am I going about it completely wrong?
推荐答案
发送
和 sendAction
街道,可以说,你可以发送一个推迟的动作,并期望它解决/拒绝它。
send
and sendAction
are one way streets, that being said, you can send a defer to the action and expect it to resolve/reject it.
var defer = Ember.RSVP.defer();
defer.promise.then(function(resolvedValue){
alert(resolvedValue);
});
setTimeout(function(){
defer.resolve('hello world');
},2000);
你的样子看起来有点像这样
Yours would look a bit like this
var defer = Ember.RSVP.defer(),
self = this;
defer.promise.then(function(){
self.closeModal();
},
function(){
alert('error');
});
this.sendAction('save', defer);
保存操作
actions: {
save: function(defer){
// if succeeded
defer.resolve();
// or if failure occurs
defer.reject();
}
}
小心,你想确保你不要不要剔除拒绝的路线,你会讨厌在这里停留模式,因为保存失败,没有失败的方法。
Be careful, you want to make sure you don't leave out the reject route, you'd hate to have the modal stuck up there because the save failed and there wasn't a failure method.
对不起我没有t转换成咖啡脚本,我想你会理解或转换和理解,我不会给你一个错误的答案。
Sorry I didn't convert to coffee script, I figure you'll either understand or convert and understand and I won't have given you a wrong answer.
这篇关于从Ember中的控制器动作返回承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!