从 Ember 中的控制器操作返回承诺? [英] Return a promise from a controller action in Ember?

查看:19
本文介绍了从 Ember 中的控制器操作返回承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件需要与控制器通信并最终执行一些清理控制器说一切正常(即,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上实现save方法

And implement the save method on FooController

App.FooController = Ember.ObjectController.extend
  save: ->
    # how can we tell the component that this was successful?

如您所见,如果 save 操作成功,我只希望 closeModal 函数执行.换句话说,只有在记录保存成功的情况下才关闭模态.

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?

推荐答案

sendsendAction 是一种方式街道,也就是说,你可以发送一个延迟到行动并期望它解决/拒绝它.

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);

你的看起来有点像这样

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.

抱歉,我没有转换为咖啡脚本,我想您要么理解,要么转换并理解,我不会给您错误的答案.

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 中的控制器操作返回承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆