Vilhelm H.
Vilhelm H.

Reputation: 1335

Ember: Detect when an object is saved

Somewhere in my ember code I have

myobject.save();

I want to detect when that saving is done. Because then the object has gotten an ID.

I know the save method returns a promise and I can use then() to execute code when saving is done. But that pattern won't work in my case.

Somewhere else in my code I am doing several things and then I want to get the ID of myobject. Then I might have to wait until the object has finished the save and has gotten the ID. I need the id because it shall be part of a transition to a dynamic route. The code in a route action handler looks like this:

myobject.DoSomeStuffAndThenSave();
....
// Do some other stuff that might take some time
....
this.transitionTo('myroute', myobject.get('id'));

I guess I need to check the isSaving flag and and in the case the isSaving flag is true, I should listen to the isUpdated event. But how do I do that?

Upvotes: 0

Views: 336

Answers (1)

Tom Netzband
Tom Netzband

Reputation: 1110

You could return another promise in your method of 'do some other stuff that might take some time' and then put your route transition in the .then() of that promise:

// models/myobject.js
export default DS.Model.extend({
  // ...

  aLongRunningMethod () {
    return new Ember.RSVP.Promise((resolve, reject) => {
      // do whatever long process you need to do here
      resolve();
    });
  }
});

// whatever file you're saving the model in
myobject.aLongRunningMethod().then(() => {
  myobject.save().then(obj => {
    this.transitionTo('myroute', obj.get('id'));
  });
});

Or if you need to save it first, you can use the methods in the opposite order:

myobject.save().then(obj => {
  obj.aLongRunningMethod().then(() => {
    this.transitionTo('myroute', obj.get('id'));
  });
});

Upvotes: 1

Related Questions