Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ');
console.log(collection);

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

like image 997
Mark Avatar asked Dec 01 '25 14:12

Mark


1 Answers

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: payload.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.

like image 96
u.k Avatar answered Dec 04 '25 04:12

u.k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!