0
votes

I have a collection of Backbone models, each having several attributes: _id, code, title, date and selected.

I want the "selected" attribute value to be true only in one of the collection models at a time. When I set a model "selected", all other models in the collection should be set to {selected:false}.

I'm thinking about two different solutions:

1) from "inside" the model: I can listen to the change of selected attribute, loop all the parent collection items, and set selected:false if _id != id of this

2) from "outside", loop over collection models, set all to selected:false, except the one who matches id I want to be selected:true.

Is there a better practice to do that? Thank you

1

1 Answers

0
votes

Here is a other solution 3)

Just as example, how to store additional data in collection. Taken from here

var MyCollection = Backbone.Collection.extend({
    meta: function(prop, value) {
        if (value === undefined) {
            return this._meta[prop]
        } else {
            this._meta[prop] = value;
        }
    },
});

var collection = new MyCollection();
collection.add(someModels);
collection.meta("selectedId", value);

You can store selectedId in collection meta propery. It will be always unique for each collection. And there is no need in 'selected' property in model.