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

1
  • did you try to update the fieldData Array with a modified copy? fieldData = this.get('fieldData'); fieldData[5]['fieldName'] = 'anotherDataPartnerCode'; this.set('fieldData', fieldData); Commented Nov 6, 2013 at 11:40

1 Answer 1

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}]
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't this work without 'this.set('fieldData', fieldData)', because your are getting reference to array so you should not need to set it again?
In this case you will update your model silently without change event and this is not good.
@RuntimeException added another example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.