【问题标题】:Handling events in ES6 Angular controllers处理 ES6 Angular 控制器中的事件
【发布时间】:2016-05-22 08:30:28
【问题描述】:

我正在为我的控制器试验 ES6 类。

以前如果我用 ui-router 监听 rootScope 事件,我可以这样做:

$rootScope.$on('stateChangeStart', function (event, toState, toParams, fromState, fromParams) { 
    console.log(toState)
}

并且 toState 将很容易访问。

我的 ES6 控制器目前看起来像这样:

class NavbarController {
  constructor ($rootScope) {
    this.name = 'navbar'
    this.$rootScope = $rootScope

    this.$rootScope.$on('stateChangeStart', this.activeNav())
  }

  activeNav () {
    console.log('This is called')
    return (event, toState, toParams) => {
      console.log('This is never called')
    }
  }
}

NavbarController.$inject = ['$rootScope']
export default NavbarController

从我读过的帖子中,我认为我在正确的轨道上但是我返回的函数没有被调用,我不知道如何访问事件参数。

那么在 ES6 角度控制器中处理事件的正确方法是什么?

【问题讨论】:

  • 您的代码不是有效的 JS。首先修复所有语法问题(括号太多,缺少箭头等。我还会在您的语句末尾添加分号。
  • 为语法错误道歉,我冲了sn-p。他们现在是正确的。我遵循standardjs,因此没有分号

标签: angularjs ecmascript-6


【解决方案1】:
activeNav () {
  console.log('This is called')
  return (event, toState, toParams) => {
    console.log('This is never called')
  }
}

您在这里使用了不正确的语法。箭头函数需要有“=>”箭头,因此它们的名字。您的代码中还有一些语法错误。考虑使用一些 IDE 或其他方式的自动语法检查。

事件的名称也是 $stateChangeStart 而不是 stateChangeStart。

【讨论】:

  • 对语法错误表示歉意,如上所述,我冲了 sn-p 并没有反映代码。因此,使用正确的语法,控制器仍然无法运行使用胖箭头声明的匿名函数返回的任何代码
  • 我注意到您也使用了错误的事件名称。它是 $stateChangeStart 而不是 stateChangeStart。
  • 当然...解决了。我被抛出了,因为 stateChangeStart 正在注册每个状态更改,而没有调用返回的函数。
【解决方案2】:

Sielakos 指出我的问题,愚蠢地使用了错误的事件。工作的 sn-p 在下面,以防它帮助其他人。

class NavbarController {
  constructor ($rootScope) {
    this.$rootScope = $rootScope
    this.$rootScope.$on('$stateChangeStart', this.activeNav())
  }

  activeNav () {
    return (event, toState, toParams) => {
      console.log(toState.name, toParams)
    }
  }
}

NavbarController.$inject = ['$rootScope']
export default NavbarController

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2017-03-02
    相关资源
    最近更新 更多