Backbone.js find next in View collection

How to find the next element's view in a Collection?

by midnightlightning

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<ul id="output">
<li>Loading...</li>
</ul>

JavaScript

MyRow = Backbone.Model.extend();
MyRows = Backbone.Collection.extend({
    model: MyRow
});

RowView = Backbone.View.extend({
    tagName: 'li',
    render: function() {
        console.log('rendering');
        this.$el.html(this.model.get('name'));
        return this; // Chain
    },
    events: {
        'click': 'show',
    },
    show: function(e) {
        var myIndex = this.model.collection.indexOf(this.model);
        var nextModel= this.model.collection.at(myIndex + 1);
        if (nextModel != undefined) {
            alert("I need to find the RowView for the Row ID "+nextModel.get('id')+" at collection index "+(myIndex+1));
        }
    }
});
RowsView = Backbone.View.extend({
    tagName: 'ul',
    render: function() {
        this.$el.html(''); // Clear
        this.model.each(function (model) {
            this.$el.append(new RowView({ model:model} ).render().el);
        }, this);
        return this; // Chain
    }
});

var items = new MyRows([
    {id: 42, name: "item 1"},
    {id: 21, name: "item 2"},
    {id: 98732, name: "item 3"}
]);
new RowsView({
    el: 'ul#output',
    model: items
}).render();