Search code examples
backbone.jscollectionsmodels

Backbone: Can I get a collection of the model in which it is found?


Can I get a collection of the model in which it is found?I would like to get a collection of models for calculating the preceding and following the model relative to the current. Can it be done in the Backbone?

var PhotoView = Backbone.View.extend({
    className: "media-item",
    template: _.template(photoItemTemplate),
    render: function(){
        var data, next;
        data = this.model.toJSON();

        this.$el.html(this.template(data));

        return this;
    },
    prev: function () {
        //this.model.collection = ??
    },
    next: function () {
       //this.model.collection = ??
    }
});

Solution

  • var collection = this.model.collection;
    var prevModel = collection.at(collection.indexOf(this.model) - 1);
    var nextModel = collection.at(collection.indexOf(this.model) + 1);