2012-03-12 55 views
0
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 

在我的班的最后一行,我得到this.footer是未定义在我的日志(悬停)。我如何使@footer像其他方法一样工作?我打电话是这样的:coffeescript class noob问题与@var

footerPanel = new FooterPanel() 
footerPanel.hint() 

所以显然我有很多脂肪箭相关的需求。我开始玩胖箭头(我以前从来没有用过),它似乎用范围来解决我的问题。感谢大家!

回答

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 
+0

好的很清楚我需要阅读关于这个胖箭头的概念。 – Fresheyeball 2012-03-12 19:08:01

+0

你必须明白,这个(@)可以改变对回调调用的上下文的依赖。 =>只是一个语法糖,它会创建一个变量_this或一个函数来将上下文绑定到一个对象。检查编译的代码。 – mpm 2012-03-12 19:13:15

1

在您的hint方法中,将setTimeout (->替换为setTimeout (=>。这可以确保无论this是什么时候hint方法被调用进入异步setTimeout调用。

+0

这有助于我有另一个问题。但我的问题在这里'userAction: - > @ footer.hover @userMoveUp,@userMoveDown#this.footer is undefined' – Fresheyeball 2012-03-12 19:03:59