I want to increment the model position attribute everytime a new model is added to the collection, I've tried converting defaults to be a function that returns a position equalled to ++collection with no success. Can anyone advise the best approach to do this?
var Col = Backbone.Collection.extend()
var Mod = Backbone.Model.extend({
defaults() {
return {
position: ++this.collection.length
}
}
})
var col = new Col([{
id: 1
}, {
id: 2
}])
col.toJSON() // returns [{id: 1}, {id: 2}]
You've got 2 distinct problems.
Using the collection's length is not enough to precisely keep track of the position.
Imagine you have 3 models, the first model is at position 1 and the last model at position 3. Then the first two models are removed and a new model is added at the end, with the collection length now being 2, you'll have incoherent positions already.
You'd need to update the position of all the models in the collection each time there's a change in the collection.
Here's a simple example using the update event.
var PositionCol = Backbone.Collection.extend({
initialize: function(models, options) {
this.listenTo(this, 'update', this.updatePositions);
},
updatePositions: function(options) {
this.each(function(model, index) {
model.set({ position: index });
}, this);
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With