Andrew
Andrew

Reputation: 238617

Can't bind events in Backbone.js view

I am trying to create a view for a piece of HTML that has already rendered on the page. I can see that the view is being instantiated, but I can't bind to any events. Here is an example:

<html>
<head><!-- backbone, etc --></head>
<body>
  <div id="myElement">
    <button id="myButton">Click me</button>
  </div>
  <script>
    new MyApp.Views.ExampleView()
  </script>
</body>
</html>

My View (coffeescript):

class MyApp.Views.ExampleView extends Backbone.View

  el: $('#myElement')

  initialize: ->
    console.log 'initialized'

  events:
    'click #myButton': 'alertMe'

  alertMe: ->
    alert('hello!')

What am I doing wrong?

Upvotes: 1

Views: 1964

Answers (1)

Andrew
Andrew

Reputation: 238617

Thanks to @muistooshort and @JayC I realized the reason the events were not binding was because my view was being defined before the document was ready (and defining el before the element had actually rendered). To fix this, you could define the view after the document was ready, or you could pass the element as an option when the view is instantiated:

<script>
  new MyApp.Views.ExampleView({el: $('#myElement')})
</script>

Or you can specify the selector as a string, and it will work correctly:

class MyApp.Views.ExampleView extends Backbone.View

  el: '#myElement'

Upvotes: 2

Related Questions