骨干事件没有解雇

Ben*_*Ben 7 javascript coffeescript backbone.js

我知道有关此事的其他帖子,但到目前为止我看到的答案没有帮助,与我的情况略有不同.

window.BotView = Backbone.View.extend
  initialize: ->
    _.bindAll @, 'alert', 'render'
    @el # by calling this here, it initializes the jQuery object

  el: $("#submit")

  model: Chatbot

  events:
    "click #submit" : "alert"

  alert: ->
    console.log("alert called")
    alert("event observed")

  render: ->
    alert("Rendered")


jQuery ->
  window.App = new BotView
  console.log App.el
Run Code Online (Sandbox Code Playgroud)

我想要的是当我点击与提交按钮idsubmit为它火的alert功能.但是,我甚至无法让这个工作.

这是怎么回事与events我简单click的处理程序#submit不工作?

我已经仔细检查过我el的初始化是否正确,但即便如此,它也无关紧要,因为点击处理程序没有使用el

谁能解释为什么这个简单的事件没有解雇?

提前致谢

Kyl*_*ers 8

在您的事件中,您要在#submit元素中查找使用#submit ID单击的元素.将其更改为

'click' : 'alert'
Run Code Online (Sandbox Code Playgroud)

它应该工作正常.

jQuery相当于你上面的内容是这样的:

$('#submit').find('#submit').click(alert);
Run Code Online (Sandbox Code Playgroud)

  • 实际上,一个更精确的翻译是`$('#submit').委托('#submit','click')`......在这种情况下并不重要,但这是一个常见的混淆点. (2认同)