简体   繁体   中英

Transient and non-dirty attribute, ember-data

I would like to declare transient attributes in my Ember models that doesn't affect the "dirty" state of the model.

At the moment, I declare them like this within the model :

eventId: DS.attr("string", {defaultValue: "", transient: true})

They are ignored in the serializer, so they wont be posted to the API :

App.ApplicationSerializer = DS.RESTSerializer.extend({
    serializeAttribute: function(record, json, key, attribute) {
        if (attribute.options.transient) { return; }
        return this._super(record, json, key, attribute);
    }
});

But the thing I also require that those properties doesn't change the "dirty" state of the object (for tracking and rollbacking without touching these).

Turns out the solution was super easy. I needed an attribute that wasn't tracked by Ember-Data (that didn't change the state and that remained untouched after a rollback).

The solution : declare the "attribute" without DS.attr . It is in fact a normal Ember Object property.

I don't know if this is the best way, but you can use a computed property:

App.Person = DS.Model.extend({
  name: Ember.computed(function(key, value) {
    if (value) {
      this.set('___name', value);
      return value;
    } else {
      return this.get('___name');
    }
  }),
  age: DS.attr('number')
});

Then just access it in a template like normal:

{{input value=model.name}}

Caveat: you'll need to trigger the computed property to initially set the value on the model, eg:

this.store.push('person', {
  id: 1,
  age: 15,
});
this.store.find('person', 1).then(function(person) {
  person.set('name', 'Kori')
});

Bonus: working jsbin

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