Search code examples
collectionsbackbone.jsmodels

Find Collection from Model in Backbone


I'm changing state on a model view and I was wondering what would be a clean way to find out the collection the model is referenced from.

Essentially it works like this: when a model is triggered to turn 'on' it needs to first go up a level and have the collection query the other models and turn any that are currently 'on' to 'off'. Right now I'm passing each model view a reference to the collection view it comes from so it can query the collection from there, but I feel that might be bad practice.


Solution

  • From the fine manual:

    Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.

    So if you change an attribute, active, on a model in a collection, then both the model and the collection will trigger "change:active" events. You could have the collection listen to itself for the appropriate "change" events:

    initialize: function() {
        _.bindAll(this, 'active_changed');
        this.on('change:active', this.active_changed);
    },
    active_changed: function(active_m) {
        if(!active_m.get('active'))
            return;
        this.each(function(m) {
            if(m.id != active_m.id) {
                console.log('Updating ' + m.id);
                m.set({ active: false }, { silent: true });
            }
        });
    }
    

    The {silent:true} on set is just there to avoid generating even more events from the internal bookkeeping; this may or may not be appropriate in your case.

    Demo: http://jsfiddle.net/ambiguous/VAnUq/

    Only having one model in the "on" state is a collection-level property so it makes sense for the collection to manage this for all of its models.