1

I have a modal dialog, which is implemented similar to what is described in the cookbook: http://emberjs.com/guides/cookbook/user_interface_and_interaction/using_modal_dialogs/

I can close the modal without any problems via an event from the template. However, I have implemented a controller for the specific modal which creates a new model with the data that has been entered via the modal. Now I want to close the dialog after the model (after the controller is done) has been created. I tried various ways to send an action from a controller to the modal, however nothing worked so far. So, two questions:

  • How do I close the modal when the action in the controller is done?

    export default ModalController.extend({
      actions: {
        create: function() {
        // do some stuff
        var newModel = this.store.createRecord('newModel', {
            name: name
        });
        newModel.save()
        // close modal
        // ... but how?
    }
    
  • As this relies on promises, I think this would close the modal after the promise is created. How do I close the modal when the actual response from the server arrives and everything went fine?

bguiz
  • 27,371
  • 47
  • 154
  • 243
st-h
  • 2,444
  • 6
  • 37
  • 60
  • Assuming you already have a `closeModal` action for when to user closes the modal, to close the modal you can use the `Em.TargetActionSupport` mixin's `triggerAction()` method to set `action: 'closeModal', target: this` or something along those lines using the methos bguiz suggested. [More info here](http://emberjs.com/api/classes/Ember.TargetActionSupport.html#method_triggerAction). – Duncan Walker Jul 04 '14 at 03:26

1 Answers1

1

Assuming you are using Ember Data for your models:

export default ModalController.extend({
  actions: {
    create: function() {
    // do some stuff
    var newModel = this.store.createRecord('newModel', {
        name: name
    });
    newModel.save().then(function success() {
        //success message and close modal
    }).catch(function failure() {
        //error message and close modal
    });
}

The basic idea here is to register success and failure callbacks for Model.save(), and close the modal dialog within those callbacks.

As for how to actually close the modal dialog, assuming that you have the implementation of closeModal within the actions hash of this same Controller, you need to invoke the action by name, through this.send()

    newModel.save().then(function success() {
        //success message and close modal
        this.send('closeModal');
    }.bind(this)) /* ... */

Be sure to call .bind() on the callback functions, so that this refers to what you would expect it to (the controller). I recall asking a question about just this a while back.

HTH!

Community
  • 1
  • 1
bguiz
  • 27,371
  • 47
  • 154
  • 243