【问题标题】:Backbone View, Event Handler and bindAll主干视图、事件处理程序和 bindAll
【发布时间】:2014-10-31 09:27:59
【问题描述】:

我有这样的事情

$ ->
  class MyView extends Backbone.View
    initialize: ->
      stuff

    $("body").on "click", ".stuff", ->
      @functionB()

    functionA: (new_date) ->
      stuff

    functionB: () =>
      stuff

  new MyView(el: $mySelector)

我想从事件处理程序中调用函数 B。
我知道我可以使用粗箭头,但我将如何使用 _.bindAll

【问题讨论】:

    标签: backbone.js coffeescript underscore.js


    【解决方案1】:

    首先,我猜$("body").on "click", ".stuff", -> 实际上在您的initialize 方法中,而您只是有格式问题。否则,您的代码没有多大意义。

    您将遇到的问题是 jQuery 控制回调函数内部的 @(AKA this)。因此,仅绑定 functionB 是不够的,因为如果没有正确的 @,您将无法访问 functionB。

    在您的特定情况下,这些都不重要,因为functionB 被定义为绑定函数(使用=>),并且您不需要在事件处理程序中使用匿名包装器,只需将函数交给on本身:

    $("body").on "click", ".stuff", @functionB
    

    如果出于某种原因你坚持绑定一个匿名函数,那么你会想要使用_.bind(或Function.prototype.bind)而不是_.bindAll; _.bindAll 将函数(按名称)绑定到特定的 @,但您想找到特定的函数(没有名称)到特定的 @,请参阅 What is the difference between these Backbone/Underscore .bind() methods? 了解更多关于差异的讨论。你会这样说:

    $("body").on "click", ".stuff", _(-> @functionB()).bind(@)
    
    # or
    
    unbound_function = -> @functionB()
    $("body").on "click", ".stuff", _.bind unbound_function, @
    

    【讨论】:

      【解决方案2】:

      由于您使用的是主干,您可以使用本机语法进行绑定,=> 或_bind 和_bindAll 的内置下划线方法。他们做同样的事情,只是你在哪里声明他们的问题。如果你在函数声明时绑定它们,那么如果你想释放事件监听器,你就可以引用它们。

      $ ->
        class MyView extends Backbone.View
          initialize: ->
            stuff
      
          $("body").on "click", ".stuff", @functionB
          # alternatively, inline as an anonymous function (then you can 
          # leave the declaration of functionB below as `->` )
          $("body").on "click", ".stuff", => @functionB(arguments...)
      
          functionA: (new_date) ->
            stuff
      
          functionB: () =>
            stuff
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多