I have a view that includes a table.
var newsIndexView = Backbone.View.extend({
...
});
Each Row in the table is another view associated with a model.
var newsItemView = Backbone.View.extend({
tagName: "tr",
...
selectRow: function(e){
this.selected = !this.selected;
$(this.el).toggleClass("selected");
if(this.selected){
$(".delete_many").on("click", $.proxy(this.remove, this));
}else{
$(".delete_many").off("click", $.proxy(this.remove, this));
}
},
...
});
The user can select rows. When 1 or more rows are selected a delete button appears. When the button (.delete_many) is selected I want to trigger the delete event for each selected newsItemView. As you can see when a row is selected I’m adding an event handler for it, and removing it when it is unselected. I was wondering if there is a better way of doing this?
Couldn’t you use delegateEvents on the view that manages the table to install the click handler once? It should fire, even if the buttons were added later (and stay around even if the buttons are removed later).
The deleteMany function would then figure out which rows are selected and remove them in a loop. Since the button belongs to the table as a whole (and not to individual rows) this seems to be more natural. It would also make it easy to have a “are you sure” confirmation dialog (that you want to pop up just once and not for every row), and using bulk delete features of your server backend (one request instead of one for each row).