2014-10-30 56 views
0

我有這樣的事情骨幹視圖,事件處理程序和bindAll

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

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

    functionA: (new_date) -> 
     stuff 

    functionB:() => 
     stuff 

    new MyView(el: $mySelector) 

我想從事件處理程序調用functionB。
我知道,我可以用脂肪箭頭,但我怎麼會跟_.bindAll

回答

0

首先的做到這一點,我猜$("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, @ 
0

,因爲你使用的骨幹,你可以使用原生語法結合,=>或內置在_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