为什么这个javascript函数没有访问上面的闭包中的变量呢?

时间:2014-08-12 09:31:57

标签: angularjs angularjs-directive

我正在尝试在Angular中创建一个指令,以显示元素是否在视口中(即用户是否滚动到它)。

然而,虽然我认为闭包会让我访问最初定义滚动侦听器的元素,但我似乎无法访问它:

MyApp.directive("inview",  ($window) ->
  link = (scope, element, attrs) ->
    sourceElement = element

    processScrollEvent = (event) ->
      console.log("They see me scrollin'");
      # once I can access the sourceElement then I'll do the
      # calculations to find out whether it's in the viewport

      # However sourceElement is not defined in this scope
      # ... how can I access it?


    angular.element($window).bind "scroll", processScrollEvent
  {
    link: link
  }
)

如何在事件处理程序中引用原始元素?

1 个答案:

答案 0 :(得分:0)

在CoffeeScript中,您可以使用=>表示法来代替经典->。它将捕获this并将其绑定到您的新函数。

试试这样:

link = (scope, element, attrs) ->
    @sourceElement = element // '@' is the same as 'this.'

    processScrollEvent = (event) =>
      console.log("They see me scrollin'");
      console.log(@sourceElement);