Mark Mark - 1 year ago 66
Javascript Question

Use Backbone model default if a attribute value is null

I have a backbone model and collection. In the model, the default attribute values are defined:

var Person = Backbone.Model.extend({
defaults: {
name: "mark",
middle: "-"

var People = Backbone.Collection.extend({
model: Person

var collection = new People();

collection.add({name: "paul", middle: null});

console.log('collection is ');

I want the default value for "middle", which is "-", to be taken if "null" is passed in for the attribute "middle". However, "null" overrides the default instead. How do I do this? The jsfiddle is here

u.k u.k

The cleanest way probably is to add a parse method and normalize the data:

var Person = Backbone.Model.extend({
  defaults: {
    name: 'mark',
    middle: '-'
  parse: function (payload) {
    return {
      name: || undefined,
      middle: payload.middle || undefined

collection.add({name: "paul", middle: null}, {parse: true});

Note that when the data is returning from the server via fetch it will automatically go through parse and there's no need to call pass the option flag.

You could do it either on the model level or at the collection level.