简体   繁体   中英

Old DS.Model properties are present when creating a new model

I have a DS.Model with some nested keys:

export default DS.Model.extend({
  name: DS.attr('string'),
  slug: DS.attr('string'),
  status: DS.attr('string'),
  config: DS.attr('', {
    defaultValue: {
      url: '',
      connections: 5,
      request_timeout: 2000,
      etc...
    }
  })
  ...
})

And a new route that creates a model for passing to a form:

export default Ember.Route.extend({
  model() {
    return this.store.createRecord('resource');
  },
  ...

After creating a new model via the form at /resource/new , on revisiting the form the config is still set to the values of the last created model.

I can see via Ember Inspector that the model is a different instance (having stored a reference to oldModel before leaving the page on the initial create):

oldModel.toString()
"<web@model:app::ember731:null>"
oldModel.get('config.url')
"http://localhost:4000/old"

newModel = $E
newModel.toString()
"<web@model:app::ember894:null>"
newModel.get('config.url')
"http://localhost:4000/old"

The issue you are experiencing is due to the fact that model.config is shared among all of your model instances, since it's created at extend time and not at create time of each model instance. This is a JavaScript concept, see this SO answer for more information.

You want each model to have it's own instance of config :

config: DS.attr({
  defaultValue() {
    return {
      url: '',
      connections: 5,
      request_timeout: 2000,
      //etc...
    };
  }
})

Also, one thing to keep in mind is that since config is a POJO, you will not have binding if you try to create observers or computed properties based on attributes within config .

I suggest using one of the following alternatives:

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