I don’t think this is an uncommon problem, but I haven’t been able to make any of the solutions I’ve found work. Here’s my [simplified] view:
class MyView extends Backbone.View
el: '#mydiv'
initialize: ->
@collection.bind 'reset', @render, @
render: ->
$(@el).html('my content')
When reset is triggered, render‘s this has been clobbered, and @el is undefined. My understanding was that the 3rd parameter on bind was supposed to take care of this, but that doesn’t appear to be happening. I am using Backbone 0.5.3.
I also tried using the “fat arrow” on render, but that didn’t work either:
render: =>
$(@el).html('my content')
Update
As Trevor Burnham pointed out below, it wasn’t a scoping issue, it was that my el property wasn’t available at page load (it get’s created later). I’m still looking for a better way to deal with that (using the id property on the view).
I don’t think the problem is that
renderis called in the wrong context, but rather that the view’selproperty is never a DOM element. Does something with the IDmydivexist at the time that you callnew MyView? If not, that’s the problem.Internally, when
elis a string, Backbone makes the callfrom the view’s constructor. If nothing matching that selector string exists,
@elwill beundefined, which is what you’re seeing.