简体   繁体   中英

Ember Data DS.Model's set function does not work?

In Ember Data, after I declare a model and commit to the store, I then retrieve it and try to set a new value for a particular field, however it is giving me this error:

Uncaught Error: <DS.StateManager:ember227> could not respond to event setProperty in state rootState.loaded.created.inFlight.
Ember.StateManager.Ember.State.extend.sendRecursively ember-latest.min.js:17
Ember.StateManager.Ember.State.extend.sendRecursively ember-latest.min.js:17
Ember.StateManager.Ember.State.extend.sendRecursively ember-latest.min.js:17
Ember.StateManager.Ember.State.extend.sendRecursively ember-latest.min.js:17
Ember.StateManager.Ember.State.extend.sendRecursively ember-latest.min.js:17
Ember.StateManager.Ember.State.extend.send ember-latest.min.js:17
DS.Model.Ember.Object.extend.send ember-data.js:2540
DS.Model.Ember.Object.extend.setProperty ember-data.js:2549
(anonymous function) ember-data.js:2682
n.set ember-latest.min.js:14
c ember-latest.min.js:14
Ember.Observable.Ember.Mixin.create.set ember-latest.min.js:15
(anonymous function)

Details (mostly boilerplate code):

/* create store */
 App.store = DS.Store.create({
    revision: 2,
    // adapter: DS.LocalStorageAdaptor.create({}),
    adapter: DS.DjangoTastypieAdapter.create({
      serverDomain:  "http://localhost:8000",
      tastypieApiUrl: 'api/v1/',
    });
});

// declare model
App.StyleData = DS.Model.extend({
    ...
    storageID: DS.attr('number', {defaultValue: 0, key: 'storageID'}),

    didCreate: function(){
        // console.log('didcreate');
    },

});

/*create new model */

App.store.createRecord(App.StyleData, {storageID: 0});
App.store.commit();

/* retrieve model and set new value for storageID */
var mod = App.store.findAll( App.StyleData );
var mod1  = mod.get('modelCache')[0];
mod1.set('storageID', 10)     // here the error above is thrown 

This error comes from attempting to modify a record while it is being saved via API call. In your example, App.store.commit() initiates an ajax operation to send the details of the new record to your API. Ajax calls are asynchronous operations, so the record enters the inFlight state until the API responds and ember-data will transition the record back to clean if everything is successful. While it is inFlight , it may not be modified.

Try this way:

var update = function(){
  if(mod.isLoaded()){
    mod1.set('storageID', 10);
  }
}.observes('mod.isLoaded')

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