2013-10-26 40 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