Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  188] [ 1]  / answers: 1 / hits: 5591  / 11 Years ago, sat, december 28, 2013, 12:00:00

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?


More From » ember.js

 Answers
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.


[#49180] Thursday, December 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leandraannabellar

Total Points: 255
Total Questions: 89
Total Answers: 89

Location: England
Member since Sun, May 21, 2023
1 Year ago
;