I'm creating a search results page using Backbone in combination with CoffeeScript and Handlebars. I have two views: one for the list of results (ListView) and the second view is for a single result (ResultView). Simplified code:
ListView = Backbone.View.extend
el: $("ul#results")
...
addItem: (result) ->
resultView = new ResultView({
model: result
})
resultView.parentView = this
this.el.append(resultView.render().el)
ResultView = Backbone.View.extend
tagName: "li"
className: "result"
events:
...
Short explanation:
- The ListView is assigned to
ul#results
- When a result is added to the listview, a ResultView is created, that has knowledge of its parent and renders itself
- For the ResultView an element
li.result
is created (default Backbone behaviour)
This is (simplified) the template I'm using to render a search result:
<li class="result">
<h1>
<a href="{{link}}">{{title}}</a>
</h1>
<p>{{snippet}}</p>
</li>
Here's my conundrum, as you may have discovered yourself: I define a li.result
in my Backbone ResultView, and in my template. What I can't do:
- Bind the ResultView to the
li.result
in my template because it doesn't exist yet in the DOM - Remove the
li.result
from my template, because I still need it to render the page server side for those who don't have JavaScript enabled
Is there a way to (elegantly) re-assign a Backbone view to an element after its been instantiated? Or put simply, can I reference ResultView to a temporary element, render the template and then move it into ul#result
? Or am I looking at it the wrong way?
Thanks!