@var的coffeescript class noob问题

时间:2012-03-12 18:56:27

标签: coffeescript

class FooterPanel

    constructor : -> # @footer works fine in the constructor
      #gather elements
      @footer        = $('footer')
      @panel         = $('ul.panel')

      #initalize states
      @isPanelUp     = false
      @userActed     = false

      #setting
      @panelSpeed    = 500

      #show panel
      @panel.filter('#'+run+'Panel').show()

      @userAction()

      #mobile love
      if device.android
        @panel.find('a').bind 'touchstart', ->
          $(this).click()

      if device.mobile
        @panel.remove()
        return false

      if device.is
        touchToggle = true
        touchTime   = null
        @footer.find('nav').bind 'touchstart', (e) ->

          return true if $(e.target).is('a')

          if touchToggle
            @userMoveUp()
            touchToggle = false
            clearTimeout touchTime
            touchTime = setTimeout @userMoveDown, 3000
          else
            @userMoveDown()
            clearTimeout touchTime
            touchToggle = true

    hint : -> # @footer has not problem working here
      setTimeout (->
        if @isPanelUp and not @userActed
          @footer.stop().animate bottom  : @panel.outerHeight() * -1, @panelSpeed, ->
            @footer.removeAttr 'style'
          @isPanelUp = false
      ), 5000
      if not @isPanelUp and not @userActed
        @footer.stop().animate bottom : 0, @panelSpeed
        @isPanelUp   = true

    userMoveUp : ->
      @userActed = true
      @footer.stop().animate bottom  : 0, @panelSpeed if not @isPanelUp
      @isPanelUp = true

    userMoveDown : ->
      if @isPanelUp
        @footer.stop().animate bottom  : @panel.outerHeight() * -1, @panelSpeed, ->
          @footer.removeAttr 'style'
      @isPanelUp = false

    userAction : ->
      @footer.hover @userMoveUp, @userMoveDown # this.footer is undefined

在我班级的最后一行,我得到了。在我的日志中(在悬停时)未定义.footer。如何使@footer像其他方法一样工作?我打电话是这样的:

footerPanel = new FooterPanel()
footerPanel.hint()

显然我有很多与胖箭有关的需求。我开始玩胖箭(我之前从未使用过它),它似乎用范围来解决我的问题。谢谢大家!

2 个答案:

答案 0 :(得分:2)

使用胖箭头(=>)将函数绑定到其初始上下文

userMoveUp : =>
  @userActed = true
  @footer.stop().animate bottom  : 0, @panelSpeed if not @isPanelUp
  @isPanelUp = true

userMoveDown : =>
  if @isPanelUp
    @footer.stop().animate bottom  : @panel.outerHeight() * -1, @panelSpeed, ->
      @footer.removeAttr 'style'
  @isPanelUp = false

答案 1 :(得分:1)

hint方法中,将setTimeout (->替换为setTimeout (=>。这样可以确保调用this方法时hint被带入async setTimeout调用。