【问题标题】:Backbone listener doesn't appear to be firing骨干侦听器似乎没有触发
【发布时间】:2013-07-18 03:01:14
【问题描述】:

我正在处理大量文件,我正在尝试在我的主干视图中创建一个监听器

appView.js.coffee

namespace "happiness_kpi", (exports) ->
  exports.appView = Backbone.View.extend

    events: 
      "click #happy" : "selection"

    selection: ->
      console.log "selection was called"

index.html.haml

%input{ :type => "image", :src => "/assets/smiley.jpg", :alt => "happy", :id => "happy" }
%input{ :type => "image", :src => "/assets/undecided.jpg", :alt => "undecided", :id => "undecided" }
%input{ :type => "image", :src => "/assets/sad.jpg", :alt => "sad", :id => "sad" }

这是我的规格:
app_view_spec.js.coffee

it "is called when one of the faces is clicked", ->
  $("body").append('<input alt="happy" id="happy" src="/assets/smiley.jpg" type="image">')
  $("body").append('<input alt="undecided" id="undecided" src="/assets/undecided.jpg" type="image">')
  $("body").append('<input alt="sad" id="sad" src="/assets/sad.jpg" type="image">')
  @subject.selection = sinon.spy()

  $("#happy").click

  sinon.assert.calledOnce(@subject.selection)

我收到错误“错误:预期的 spy 被调用一次但被调用 0 次”有人知道为什么单击输入时没有触发事件吗?

提前致谢。

【问题讨论】:

  • click() 用括号触发事件可能吗?

标签: backbone.js


【解决方案1】:

如果问题不是在调用click() 时括号的明显拼写错误,那么我在想的另一件事是 Backbone 中的事件范围在 View 元素内。这意味着 View 不能列出发生在自身外部的事件(当然可以,但不能简单地使用 events 对象)。

在测试开始时尝试这样做:

@subject.setElement($("body"));

这会将 View el$el 设置为 body 标记,因此您要附加的图像实际上会进入您的 View 并且将触发事件。

【讨论】:

  • 我尝试设置@subject.setElement($("body"));,但我收到el$el 未定义的错误。我试图在控制台中摆弄它,但在那里我也没有太多运气。我发现部分问题出在我的模板上,但我已经解决了这个问题,然后回到手头的问题。
【解决方案2】:

所以经过大量研究和修补,我似乎已经找到了答案。问题绝对是我将图像附加到 iframe 的方式。问题是测试似乎在 iframe 之外创建了一个新元素,并且对页面不可见。 $('#happy').click() 执行正确,但是,它在 iframe 中不存在的东西上执行。

所以我的解决方案:

app_view_spec.js.coffee

beforeEach ->
  $("body").append('<div id="display"></div>')

afterEach ->
  $("body").append('<div id ="display"></div>').remove()

it "is called when one of the faces is clicked", ->
  @subject.emotionSelection = sinon.spy()
  @subject.delegateEvents()

  $("input#happy").click()

  sinon.assert.calledOnce @subject.emotionSelection

appView.js.coffee el: '#display'

initialize: ->
  @render()

events: ->
  'click #happy': @emotionSelection

render: ->
  @$el.html HandlebarsTemplates.faces()

emotionSelection: ->
  console.log "hello"

我发现这样做是一种更好的方法,我只是将我的 HAML 附加到 iframe,而不是尝试单独附加每个图像。学过的知识。感谢您的帮助!

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 2017-09-27
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多