Question

I have a backbone.js model with nested objects for fieldData as shown in image below.

I know I can remove whole attribute like this:

this.unset('fieldData');  

But how do I remove an individual objects (eg:- dataPartnerCodes) in that attribute.

Does backbone provide any tools for this?

enter image description here

Was it helpful?

Solution

Backbone itself doesn't have such instruments but you can create a method for easy model usage.

var Model = Backbone.Model.extend({
  // Remove by passed index
  removeFieldDataAt : function (index) {
    var fieldData = this.get('fieldData');
    fieldData.splice(index, 1);
    this.set('fieldData', fieldData);
  }
});
var model = new Model({fieldData : [{id:1}, {id:2}, {id:3}]});
model.removeFieldDataAt(1);
console.log(model.toJSON()); // [{id:1}, {id:3}]

Another example:

var Model = Backbone.Model.extend({
  removeFieldDataByCriteria : function (criteria) {
    var fieldData = this.get('fieldData');
    var fields = _.where(fieldData, criteria);
    _.each(fields.reverse(), function (field) {
      fieldData.splice(fieldData.indexOf(field), 1);
    });
    this.set('fieldData', fieldData);
  }
});
var model = new Model({fieldData : [{id:1,visible:true}, {id:2,visible:false}, {id:3,visible:true}]});
model.removeFieldDataByCriteria({visible:true});
console.log(model.toJSON()); // [{id:2, visible:false}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top