0

调整窗口大小时,我试图调用一些函数。changePosition 函数调用得很好,但是 tryPrint 函数遇到了“未捕获的类型错误:对象 [object global] 没有方法 'tryPrint'”错误。我不明白为什么会这样。我尝试在调整大小侦听器中添加一个“this”参数,但这并没有引导我到任何地方......

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
4

1 回答 1

2

The problem is that the value of this (AKA @ in CoffeeScript) inside a function depends on how the function is called unless you've bound the function to a specific object. You're doing this to bind the function to an event:

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

jQuery's on will set this to window when calling changePosition in this case:

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.

If you want this to be the view then use a fat-arrow (=>) when defining the method:

changePosition: =>
    @tryPrint()

Other options:

  1. Use a bound function:

    $(window).on('resize', @changePosition.bind(@))
    $(window).on('resize', _(@changePosition).bind(@))
    $(window).on('resize', $.proxy(@changePosition, @))
    #...
    
  2. Manually set this:

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

Using => is probably the easiest as you'll want to off the handler when destroying your view and => will keep function references right.

于 2013-10-26T23:07:09.930 回答