Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically increment backbone model attribute value on add?

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}]
like image 487
styler Avatar asked Feb 18 '26 04:02

styler


1 Answers

You've got 2 distinct problems.

  1. Set Backbone model's defaults based on a collection attribute
    but if it's only for the position, this may not be necessary.
  2. Keeping track of the position of a model inside a collection.

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);
    },
});
like image 116
Emile Bergeron Avatar answered Feb 19 '26 18:02

Emile Bergeron



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!