2013-10-26 42 views
0

我想調整窗口大小時調用幾個函數。 changePosition函數被調用的很好,但tryPrint函數受到「Uncaught TypeError:Object [object global]」沒有方法'tryPrint'「錯誤的困擾。我不明白爲什麼會這樣。我嘗試添加一個「這個」參數將調整大小的監聽器,但沒有導致我在任何地方......從其他函數調用Backbone視圖函數的問題

class App.Views.Pages.WorkView extends Backbone.View 

    template: JST["backbone/templates/pages/work"] 

    initialize:() -> 
    this.render() 
    $(window).on('resize', this.changePosition) 

    tryPrint: -> 
    console.log("TRYING") 

    changePosition: -> 
    this.tryPrint() 

    render: => 
    $(@el).html(@template()) 
    return this 

回答

2

的問題是,this(在CoffeeScript中AKA @)函數裏面的值取決於如何函數被調用,除非你已經將該函數綁定到一個特定的對象。你這樣做的功能結合到一個事件:

$(window).on('resize', this.changePosition) 

jQuery的on調用在這種情況下changePosition時將設置thiswindow

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector .

如果你想this是視圖,則定義方法時使用fat-arrow (=>)

changePosition: => 
    @tryPrint() 

其他選項:

  1. 使用綁定功能:

    $(window).on('resize', @changePosition.bind(@)) 
    $(window).on('resize', _(@changePosition).bind(@)) 
    $(window).on('resize', $.proxy(@changePosition, @)) 
    #... 
    
  2. 手動設置this

    that = @ 
    $(window).on('resize', -> that.changePosition()) 
    

使用=>可能是最簡單的,你會想off處理程序時破壞你的視野和=> w生病保持功能參考正確。

+0

我根本不知道胖箭頭有什麼不同。對此,我真的非常感激! – user2245942