I have the following Backbone (in coffeescript) view where i pass an array and try to append each item to the el. However, I keep coming up with an empty el.
ItemTagList = Backbone.View.extend
className : "itemTagsContainer"
initialize : (tags) ->
this.render(tags.taglist)
render: (taglist) ->
taglist.forEach (tag) ->
tag_span = _.template($("#tag").html(), {tag : tag} )
$(this.el).append(tag_span)
console.log(tag)
The template $("#tag") looks like this:
<a class='tag' href="/items?tagged_with=<%= tag =>"><%= tag =></a>
Upon rendering, the above will correctly iterate over the taglist, so I know that the taglist is properly passed to the Backbone View, as well as to the render function.
But if I do the following
itemTagList = new ItemTagList
taglist : ["Tag1", "Tag2"]
console.log(itemTagList.el)
I always get the empty el, i.e.
<div class="itemTagsContainer"></div>
instead of
<div class="itemTagsContainer">
<a class='tag' href="/items?tagged_with=Tag1">Tag1</a>
<a class='tag' href="/items?tagged_with=Tag2">Tag2</a>
</div>
which is what I was hoping to get.
Can anyone help?
You just have a context problem inside your
forEachcallback function; the@(AKAthis) will be the global object (windowin a browser) sothis.elisn’t what you think it is. You can get around this by using a fat-arrow (=>) when defining your callback function:I’ve also switched to
@$elsince your view will already have a cached version of$(@el).The context in a
forEachcallback depends on what mode you’re in:I’d recommend using
=>so that you don’t have to worry about it; alternatively, you could use thethisArg:but that tends to be a bit ugly and cumbersome in CoffeeScript.