neph
neph

Reputation: 743

Backbone table row view, with just one eventlistener?

Basically what I want todo is have one Backbone view for each row of my HTML table, and I can easily accomplish this when I render my table I instantiate a backbone.view for each tr, and that would be the "el" of the view.

However, this will result in each tr having an eventlistener, which is not very efficient. Is there a way to accomplish the same thing ie having the "el" of each row-view be the tr but that all events are delegated from the table element so that only one eventlistener exists?

Perhaps having a parent view for the table and somehow delegate all events, or I don't really know how to go about this in a good way, thanks.

Upvotes: 0

Views: 1322

Answers (1)

fguillen
fguillen

Reputation: 38812

The normal approach to this is having a TableView and multiple RowViews. TableView will be associated with a Collection and it will instantiate as many RowViews as needed iterating over this Collection.

Also TableView will be listening to changes in the Collection and creating and removing RowView instances if the Collection change.

RowView will be listening to changes on each of the Models in the Collection. And listening to User interactions over active DOM Elements associated to each Model.

I don't see any problem on this. And I think is the most intuitive, maintainable, and elegant structure.

If you really think is better having TableView listening to events in all the rows at once it is not a problem, try this:

var TableView = Backbone.View.extend({
  events: {
    "click tr a.remove", "remove"
  },

  remove: function( event ){
    console.log( "row-id", $(event.target).attr( "data-row-id" ) );
  }
});

Just be sure each row can be identified by the TableView by any special attribute as data-row-id in the example.. but them you will have to go to the Collection, search for the concrete Model and act, when consuming this event directly in the RowView you have direct access to the Model and everything works more natural.

Actually I don't think you are gonna achieve better performance, I think the underhood jQuery will create the same number of event listener.

Upvotes: 3

Related Questions