minimalis
minimalis

Reputation: 1953

Multiple table rows as a backbone.js view?

So I have a grid of data, and each item in the grid has an associated model and view. I need to render each item as two table rows to achieve the desired UI. (No, it wasn't my design...)

First attempt: in the view's render() method, just render two rows and add them to this.el. Then I append each view to the table, and discover that every pair of rows has been wrapped in a <div>. Invalid HTML and the layout is all wrong.

Ok, second attempt: render two rows in the view again, but instead of appending the entire view to the table, I just append the child rows by using tableItemView.$("tr"). Hooray, it works! But hold on ... the row events have now stopped firing. I discover this is because backbone uses jQuery.delegate, so all the events were delegated to the original el which is no longer part of the table.

I love backbone's clean architecture but struggle to find a nice solution to this. Any ideas?

Upvotes: 11

Views: 3911

Answers (3)

satchmorun
satchmorun

Reputation: 12477

An option is to simply create 2 small views that each reference the same model, one for each row.

Depending on how integrated the 2 rows need to be (perhaps moved/sorted as a unit), you could have a 'controller'-like view that creates the subview and orchestrates their behavior.

Upvotes: 0

Solsys
Solsys

Reputation: 363

Setting

tagName: 'tbody' 

should allow you to group the related tr tags together without breaking the table and still allow this.el to work.

Upvotes: 19

Jason Miesionczek
Jason Miesionczek

Reputation: 14448

In your view object, what is your tagName property set to?

From the docs:

this.el is created from the view's tagName, className, and id properties, 
if specified. If not, el is an empty div

You probably want to set

tagName: 'tr'

And then in render():

$(this.el).html("<td>content for row one</td>").append("<tr><td>content for row two</td></tr>");

That may not work exactly, but you get the idea.

Upvotes: 1

Related Questions