0

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

Roy M J
  • 6,926
  • 7
  • 51
  • 78
RuntimeException
  • 1,135
  • 2
  • 11
  • 25
  • did you try to update the fieldData Array with a modified copy? `fieldData = this.get('fieldData'); fieldData[5]['fieldName'] = 'anotherDataPartnerCode'; this.set('fieldData', fieldData);` – erotte Nov 06 '13 at 11:40

1 Answers1

1

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}]
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55