I’m using CoffeeScript with a Backbone view class. When I include the class in the same page as the html everything works fine. When I use a separate file and export the class, it initialises but the events aren’t mapped.
The class file is:
root = exports ? this
class root.AppView extends Backbone.View
el: $("#app")
events:
'click #appBtn1' : 'handleEvent'
'click #appBtn2' : 'handleEvent'
initialize: =>
alert 'init'
handleEvent: =>
alert 'event'
Only the initialize function fires. What do I need to alter to map the events when the code is in a separate class?
The problem is that the function
runs immediately when you define the class. So when the class is in a separate file, the
#appelement doesn’t (necessarily) exist in the DOM yet.What you should be doing is using a selector string instead, which Backbone will pass to the
$function when the class is instantiated: