Basically, in Backbone & coffeescript, I’m pulling in tweets from the Twitter API. Fetching the JSON works, however loading the template into html does not. Pulling in the template works within the render function, however does not work within the @Tweets.fetch() function.
The line of code which seems to be failing is..
$(@.el).html(_.template($('#leTweets').html(), {tweets: tweets.models, _:_} ))
My View looks like this…
class HomeView extends Backbone.View
constructor: ->
super
initialize: ->
@Tweets= new TweetsCollection
render: ->
@loadResults()
loadResults: ->
@Tweets.fetch({
success: (tweets) ->
$(@.el).html(_.template($('#leTweets').html(), {tweets: tweets.models, _:_} ))
error: ->
alert('Error!')
})
My HTML looks like this:
<script type="text/template" id="leTweets">
<div data-role="header" data-position="fixed">
<h1>TWEETS</h1>
</div>
<div data-role="content">
<h3>Tweets</h3>
<ul class="tweets">
<% _.each(tweets, function (tweet) { %>
<li><%= tweet.get('text') %></li>
<% }); %>
</ul>
</div>
</script>
And my collection looks like this:
class PropertyCollection extends Backbone.Collection
constructor: ->
super
url: ->
'http://search.twitter.com/search.json?q=' + @query + '&page=' + @page + '&callback=?'
parse: (resp, xhr) ->
resp.results
page: 1,
query: "Backbone"
Any help would be much appreciated, thanks.
I believe the issue is that the scope of “this” (@ in coffeescript) in your success handler is not your HomeView, but is “window”. Therefore ‘window.el’ does not exist.
The simple solution is to use the ‘fat arrow’ to set the scope of the event handler to the view:
This jsFiddle shows a working example: http://jsfiddle.net/edwardmsmith/PwMSP/6/