【问题标题】:what does the `run() {}` do in javascript/Aurelia?`run() {}` 在 javascript/Aurelia 中有什么作用?
【发布时间】:2016-07-12 17:32:53
【问题描述】:

我在 Aurelia 网站上看到,其中一篇文章使用了run() {}。这种方法一般有什么作用?它是生命周期钩子还是新的 Javascript 2016 方法?

http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/cheat-sheet/7

import {Redirect} from 'aurelia-router';

export class App {
  configureRouter(config) {
    config.title = 'Aurelia';
    config.addPipelineStep('authorize', AuthorizeStep);
    config.map([
      { route: ['welcome'],    name: 'welcome',       moduleId: 'welcome',      nav: true, title:'Welcome' },
      { route: 'flickr',       name: 'flickr',        moduleId: 'flickr',       nav: true, auth: true },
      { route: 'child-router', name: 'childRouter',   moduleId: 'child-router', nav: true, title:'Child Router' },
      { route: '', redirect: 'welcome' }
    ]);
  }
}

class AuthorizeStep {
  run(navigationInstruction, next) {
    if (navigationInstruction.getAllInstructions().some(i => i.config.auth)) {
      var isLoggedIn = /* insert magic here */false;
      if (!isLoggedIn) {
        return next.cancel(new Redirect('login'));
      }
    }

    return next();
  }
}

【问题讨论】:

  • It's a lifecycle method 使用 ES2015 方法语法编写。搜索您链接到的站点,您将看到使用run 方法的各种服务。这在 ES2015 中并不是什么新鲜事物。
  • 就是这样!谢谢!

标签: javascript aurelia


【解决方案1】:

您可以在路由器配置中添加多个管道步骤。每个管道都必须实现PipelineStep接口:

interface PipelineStep {
  /**
   * Execute the pipeline step. The step should invoke next(), next.complete(),
   * next.cancel(), or next.reject() to allow the pipeline to continue.
   *
   * @param instruction The navigation instruction.
   * @param next The next step in the pipeline.
   */
  run(instruction: NavigationInstruction, next: Next): void;
}

(source code)

如您所见,必须有run 方法。在稍后的某个时间点,所有步骤中的run 方法将被执行。

所以你的问题的答案是:不,这不是 ES2015 引入的东西,而是必须遵循约定管道步骤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多