8
votes

I want to make transition after a create a post.

post/new > click submit > rails backend successfully create post and response a json > redirect to newly created post's path

in ember_data_example github source code. they use this approach

 transitionAfterSave: function() {
     // when creating new records, it's necessary to wait for the record to be assigned
     // an id before we can transition to its route (which depends on its id)
     if (this.get('content.id')) {
       this.transitionToRoute('contact', this.get('content'));
     }
 }.observes('content.id'),

It works fine, because The model has ID of null when model created, and its ID would change when model saving is successful because this function observes change of models ID.

But maybe, this function will be executed whenever model's ID property is changed. I'm finding some more semantic way.

I want transition to be executed when the model's status is changed to 'isDirty' = false && 'isNew' == true form 'isDirty' = true, 'isNew' = false.

How can I implement this?

3

3 Answers

20
votes

Ideally, the id is not supposed to change. However, you are correct, semantically, this method doesn't seem right.

There is a cleaner way to do this:

save: function(contact) {
  contact.one('didCreate', this, function(){
    this.transitionToRoute('contact', contact);
  });

  this.get('store').commit();
}

UPDATE 2013-11-27 (ED 1.0 beta):

save: function(contact) {
  var self = this;
  contact.save().then(function() {
    self.transitionToRoute('contact', contact);
  });
}
4
votes

Note for Ember 2.4 It is encoraged to handle saving actions in the component or route level (and avoid controllers). Here's an example below. Note the id on the model object in the transition. And note how we use transitionTo and not transitionToRoute in the route.

  actions: {
    save() {
      var new_contact = this.modelFor('contact.new');
      new_contact.save().then((contact) => {
        this.transitionTo('contact.show', contact.id);
      });
    },
3
votes
    actions: {
        buttonClick: function () {
            Ember.debug('Saving Hipster');
            this.get('model').save()
                .then(function (result) {
                    this.transitionToRoute('hipster.view', result);
                }.bind(this));
        }
    }