Return a promise from a controller action in Ember?

淺唱寂寞╮ 提交于 2019-12-28 05:34:18

问题


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?

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

And I can instantiate the component inside a template named foo,

{{modal-form save="save" ...}}

And implement the save method on FooController

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

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?


回答1:


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

save action

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.



来源:https://stackoverflow.com/questions/20810162/return-a-promise-from-a-controller-action-in-ember

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!