Saving Only Dirty Attributes

For certain applications it’s important to send only dirty attributes of a model to the backend.

For example, an autosave feature on a partially-filled form or payload optimization for slow connections.

Customizing the serializer

Luckily, Ember Data provides a clean way to detect dirty (updated) fields, and that is:

model.changedAttributes()

We know that the right place to customize payloads is the serializer, in particular the model’s serializer.

If the model backing the form was a Post, we would logically override the PostSerializer.

We will simply define a custom serializeAttribute function that serializes that particular attribute if and only if:

// app/serializers/post.js

export default DS.JSONAPISerializer.extend({

  serializeAttribute(snapshot, json, key, attributes) {    
    if (snapshot.record.get('isNew') || snapshot.changedAttributes()[key]) {
      this._super(snapshot, json, key, attributes);
    }
  }

});

If these conditions are not met, this._super() is not called and the attribute will not be serialized.

In the case that we want to prevent nulls (fields with no set value) from being included in the payload, we can modify the above function to check for snapshot.attr(key).

Enjoyed this article? Don't miss my next one!

Leave me your e-mail for content that will help you master Ember:

Do you want to master Ember fast?

Leave me your e-mail for helpful updates delivered straight to your inbox.

(A few e-mails per month. No BS. Unsubscribe anytime!)