Non-persistent attributes in EmberJS

后端 未结 4 1240
时光取名叫无心
时光取名叫无心 2021-02-13 19:48

Does anyone know of a way to specify for an Ember model an attribute which is not persisted?

Basically, we\'re loading some metadata related to each model

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 20:35

    Update

    This answer is most likely out of date with the current releases of Ember Data. I wouldn't use anything in my answer.


    I'm answering this question for reference, and because your comment indicated that the record remains isDirty, but here is my solution for read-only, non-persistent, non-dirty attributes.

    Overriding the addAtributes method in your Serializer prevents readOnly attributes from being sent to the server, which is probably exactly what you want, but you need to extend (or reopen) your adapter to override the dirtyRecordsForAttributeChange to prevent the record from becoming dirty:

    App.CustomAdapter = DS.RESTAdapter.extend({
      dirtyRecordsForAttributeChange: function(dirtySet, record, attrName, newValue, oldValue) {
        meta = record.constructor.metaForProperty(attrName);
        if (meta && meta.options.readOnly) { return; }
        this._super.apply(this, arguments);
      };
    });
    

    Then you can use readOnly attributes like so:

    App.User = DS.Model.extend({
      name: DS.attr('string', {readOnly: true})
    });
    
    user = App.User.find(1);      # => {id: 1, name: 'John Doe'}
    user.set('name', 'Jane Doe'); #
    user.get('isDirty')           # => false
    

    This setup is working for me.

提交回复
热议问题