Nick Brown
Nick Brown

Reputation: 1167

Backbone - Possible to get the collection from a model

I'm wondering if there's a way to get a reference to a collection from one of its models. For instance, if any of the people in the collection below are somehow aware of belonging to a collection, or multiple collections. Fiddle

(function() {
window.App = {
    Models: {},
    Views: {},
    Collections: {}
};

App.Models.Person = Backbone.Model.extend({
    defaults: {
        name: 'John',
        phone: '555-555-5555'
    }
});

App.Views.Person = Backbone.View.extend({
    tagName: 'li',

    template: _.template("<%= name %> -- <%= phone %>"),

    render: function(){
        var template = this.template( this.model.toJSON() );

        this.$el.html( template );

        return this;
    }
});

App.Collections.People = Backbone.Collection.extend({
    model: App.Models.Person 
});

App.Views.People = Backbone.View.extend({
    tagName: 'ul',

    add: function(person){
        var personView = new App.Views.Person({ model: person });

        this.$el.append( personView.render().el );

        return this;
    },

    render: function() {
        this.collection.each(this.add, this);

        return this;
    }
});


})();

var peeps = [ { name: 'Mary' }, { name: 'David' }, { name: 'Tiffany' } ];

var people = new App.Collections.People(peeps);

var peopleView = new App.Views.People({ collection: people });

peopleView.render().$el.appendTo('body');

Upvotes: 17

Views: 9640

Answers (1)

Cianan Sims
Cianan Sims

Reputation: 3429

Each model has a property called collection. In your fiddle, adding console.log(people.models[0].collection) will print out the collection.

Looking through the source code, it looks like this is what's used to do things like remove a model from a collection when the model's destroy() method is called.

Update: see this updated fiddle which creates three person models and two collections. It prints them to the console. It looks like model.collection only refers to the first collection the person was added to, not the second.

Upvotes: 25

Related Questions