简体   繁体   中英

EmberJS: how to send an action from a controller?

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM