1

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?

4

1 回答 1

2

感谢@muistooshort@JayC ,我意识到事件没有绑定的原因是因为我的视图是在文档准备好之前定义的(并且el在元素实际呈现之前定义)。要解决此问题,您可以在文档准备好后定义视图,或者您可以在实例化视图时将元素作为选项传递:

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

或者您可以将选择器指定为字符串,它将正常工作:

class MyApp.Views.ExampleView extends Backbone.View

  el: '#myElement'
于 2013-02-03T06:11:25.497 回答