I have a standard list view setup with backbone that looks something like below. I have an instance where I need to remove an item, which is done in a remove function that destroys the model and unrenders the element. However just before the destroy/unrender I would like to select the previous element in the list.
Is there a good way to do this in backbone, right now the only thing I can think of is to do it with some jQuery, but I would like to know if there is a way to do go prev/next within backbone internally. Or would I need to set that up manually when appending my list items?
App = (function(Backbone, _){
var Item = Backbone.Model.extend(
{
defaults:
{
part1: 'hello',
part2: 'world'
}
});
var ItemList = Backbone.Collection.extend({
model: Item
});
var ListRow = Backbone.View.extend(
{
tagName: 'li',
initialize: function()
{
_.bindAll(this, 'render');
},
render: function()
{
$(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>');
return this;
},
remove: function()
{
//toggle previous element if exists before destory
$this.model.destroy();
},
toggle: function()
{
this.$el.addClass('active');
}
});
var ListView = Backbone.View.extend(
{
el: $('#layout_content'),
events:
{
'click button#add': 'addItem'
},
initialize: function()
{
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new TableList();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function()
{
var self = this;
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
_(this.collection.models).each(function(item){ // in case collection is not empty
self.appendItem(item);
}, this);
},
addItem: function()
{
this.counter++;
var item = new Item();
item.set({part2: item.get('part2') + this.counter});
this.collection.add(item);
},
appendItem: function(item)
{
var listRow = new ListRow({
model: item
});
$('ul', this.el).append(listRow.render().el);
}
});
var app = function(initialModels)
{
this.start = function()
{
this.listView = new ListView({collection: new ItemList(initialModels)});
};
};
return app;
})(Backbone, _);
var app = new App([{"id":"95","note_title":"can we find the title"},{"id":"93","note_title":"some title"}]);
app.start();
There seems to be no direct way inside backbone to accomplish this. I think that best that you can do, in the way of implementing this in Backbone, is to give each listrowview an index number when you add them to the listview and store the instances in an array within the listview. When destroying just go
newindex = indexnumber +/- 1and then show the view residing in the new index.