【问题标题】:Backbone event for click WITH CSS selector not firing单击 WITH CSS 选择器的主干事件未触发
【发布时间】:2012-02-27 18:32:40
【问题描述】:

我讨厌把这个问题放在那里(连同其他百万个“事件未触发”问题),但无论出于何种原因,其他问题及其各自的答案对我都不起作用。

这是脚本“text/template”标签内的模板标记,id 为“display_template”

<div class="display_data">
    <a class="remove">X</a>
    <div class="grid_6">
            <%= Data %>
    </div>
</div> 

这是我在 Coffeescript 中的 Backbone 视图

$ ->
  class window.WebsiteView extends Backbone.View

    displayTemplate: _.template $('#display_template').html()

    events:
      'click .remove': 'clicked'

    render: ->
      $(@el).html @displayTemplate @model.toJSON()
      @

    clicked: ->
      console.log 'clicked'

更新

看起来我可能没有正确实例化视图,它是从集合和集合的视图中设置的。

  class window.Websites extends Backbone.Collection
    model: Website


  class window.WebsitesView extends Backbone.View
    template: _.template $('<div />').html()

    render: ->
      $(@el).html @template
      @collection.each @renderWebsite
      @

    renderWebsite: (website) =>
      website.attributes.Index = @collection.indexOf website

      view = new WebsiteView
        model: website

      $(@el).append view.render().el

如果我从 click 事件中删除 css 选择器,'clicked' 方法将为特定视图触发,但在我添加 css 选择器后停止工作。我怀疑这可能与 @el 未正确绑定有关,但我很困惑,我希望有人能用我的特定语法为我指明正确的方向。

【问题讨论】:

  • 你是如何实例化你的 MyView 的?代码很好:jsfiddle.net/ambiguous/8EmwS
  • 更新了设置视图的位置,感谢您的帮助。
  • 从您的浏览器执行“检查元素”,看看&lt;a class="remove"&gt;X&lt;/a&gt; 是否在标记中,就像它应该的那样。还要考虑是否还有其他内容(就 z-index 而言)。
  • 是的,它肯定在标记中。我没有任何可以叠加在上面的东西。
  • 我想到了两件事:首先,您是否使用 console.log()s 在内部检测了主干以查看您要绑定的内容?其次,这两个示例的模板实例都相当糟糕。它更像是template: $('#templateid').html(); ... _.template(@template, @collection.toJSON()); 随你的咖啡脚本心血来潮删除括号。

标签: backbone.js coffeescript


【解决方案1】:

让我们看一下 Backbone 源代码。在delegateEvents 方法中,我们有:

if (selector === '') {
  this.$el.bind(eventName, method);
} else {
  this.$el.delegate(selector, eventName, method);
}

你说当没有选择器时,你的代码可以工作; but when the selector is '.remove', it doesn't.

一种可能性:您使用的是旧版本的 jQuery。 delegate 是在 1.4.2 中添加的。

另一种可能性:可能有另一个事件处理程序,绑定在其他地方,正在执行preventDefault 或返回false,防止事件冒泡到el。要找到这些,请使用浏览器的检查器并转到 .remove 链接上的“事件侦听器”以及围绕它的任何内容。

【讨论】:

  • 仔细检查了元素,没有附加任何东西,我敢肯定这是我在某处犯的愚蠢错误
  • 这可能是最好的答案,因为这是您应该从 console.log() 的位置,以查看您绑定的内容和位置。
【解决方案2】:

查看添加“preventDefault”调用是否有帮助:

clicked: (event) ->
  event.preventDefault()
  console.log 'clicked'

【讨论】:

  • 这没有意义。调用event.preventDefault() 会如何影响console.log 行是否运行?
  • 我在想点击a标签可能会触发发起新页面请求的普通浏览器行为,这可能会掩盖console.log输出或阻止当前页面进一步执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多