Save only certain model attributes in Backbone.js

Save only certain model attributes in Backbone.js

When calling in Backbone.js all model attributes will be persisted (sent to the server).

It may be done by passing a specific option argument to toJSON method. It is done in save method. You may create a base class and extend all your models from that base class. This way all extended classes that will have whitelistSaveAttributes will whitelist attributes on saving:

whitelistSaveAttributes: ['body', 'message']

# Proxy save method
save: (key, val, options)->
  # If key is an object then second argument is options
  if not key? or typeof key is 'object'
    options = val or {}
    val = options

  if @whitelistSaveAttributes? and @whitelistSaveAttributes.length
    options.JSONType = 'save', key, val, options)

# Check for attributes that are functions
toJSON: (options = {})->
  json =

  # On save send only whitelisted attributes
  if options?.JSONType is 'save'
    json = _.pick.apply(this, [json].concat(@whitelistSaveAttributes))

  return json