I am using Backbone.js for my project.
Sorry, I am a Backbone newbie, therefore I may be missing something very trivial.
This is an HTML snippet:
<table id="notes" class="table">
<thead>
<tr><th>title</th><th>comment</th></tr>
</thead>
<tbody id="notesTableBody">
</tbody>
</table>
And this is the Backbone code that it is supposed to “inject” HTML in that snippet:
App.view.NoteListView = Backbone.View.extend({
el:"tbody#notesTableBody",
initialize:function () {
this.model.bind("reset", this.render, this);
},
render:function (eventName) {
_.each(this.model.models, function (note) {
$(this.el).append(new App.view.NoteListItemView({model:note}).render().el);
}, this);
return this;
}
});
For clarity, I haven’t pasted the NoteListItemView code because I don’t think it is relevant.
My problem is that the HTML code rendered by Backbone is as follows:
<table id="notes" class="table">
<tbody id="notesTableBody">
<tr><td>title 1</td><td>comment 1</td></tr>
</tbody>
</table>
Basically Backbone removed the thead from the table.
I don’t understand why – how can I make sure Backbone doesn’t remove it?
Your
NoteListViewwon’t write anything outside of itsel(for example: http://jsfiddle.net/ambiguous/cFvX2/) so your problem is elsewhere.My guess was that you were doing something equivalent to this:
and that will completely replace the content of the
#notestable with just the<tbody>(i.e.NoteListView‘sel).There are couple ways around your problem. You could just call
renderand ignore what it returns:That’s pretty much what my first demo fiddle did.
Or you could use
idandtagNameinstead ofel:and then
appendthe view’selto$('#notes'):Demo: http://jsfiddle.net/ambiguous/HTAkM/
You could also let the caller specify the
el:and then
renderintoelwithout caring aboutrender‘s return value:Demo: http://jsfiddle.net/ambiguous/2Ptkp/
And while I’m here, you don’t need to
$(this.el)anymore, recent versions of Backbone providethis.$elfor your views:If your view is wrapping a collection, you should use
this.collectioninstead ofthis.model:Views treat the
collectionoption specially just likemodel:Backbone collections also have several Underscore methods mixed in so you don’t need to say this:
you can call
eachright on the collection:Also, if you’re binding to a
"reset"event:you probably want your
renderto clear out theelbefore appending more things to it:If you don’t
emptytheelyou’ll be adding more things to it when you probably mean to replace its contents with new things.