user3568719
user3568719

Reputation: 1056

Emberjs save record Mockjax

I want to save a record and add to an existing list in emberjs. I use two forms to simulate multiple models with the same property. But the main focus is on the 2nd one with books.

http://jsbin.com/pexolude/46

I use books: store.find('book',{}) where i dont really know whats the empty object is for but it prevents to have the book record to appear on the list. I only want to have it after the save.

Is it possible to set mockjax's respons accordingly the posted data, so i sont have to use a hardcoded JSON?

Upvotes: 0

Views: 192

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

Ember-form doesn't appear to handle switching models out underneath it. When you do store.find('foo',{}) you're tricking Ember into finding by query. When it finds by query it only includes the records returned in the results in the collection. When you do find('foo') it returns a live collection that updates when any record is added or removed from the store. You can do a find, then toArray to avoid having it be a live collection. Then you can manually add the record to the collection, and swap out the currently editing model with a new record. Unfortunately, as stated before Ember-forms doesn't update the binding and keeps using the same record.

App.IndexRoute = Ember.Route.extend({
    model: function() {
        var store = this.store;
        return store.find('book').then(function(books){
          return {
            books: books.toArray(),
            book:store.createRecord('book'),
            person: store.createRecord('person'),
            category: [{id:1,"name":"Fantasy"},{id:2,"name":"Drama"}]
          }
        });
    } 
});

App.IndexController = Ember.Controller.extend({
  actions: {
    some_action: function() {
      var self = this;
      this.get('model.book').save().then(function(record){
        var newRecord = self.store.createRecord('book');
        self.get('model.books').pushObject(record);
        self.set('model.book', newRecord);
        console.log(newRecord);
      }, function(error){
          console.log('fail');
      });


    }
  }
});

http://jsbin.com/pexolude/48/edit

Upvotes: 2

Related Questions