节奏和余烬,我如何让它在所有路由中工作而不重复代码

Pace and ember, how do I make it work in all routes without repeating code

本文关键字:工作 路由 代码 余烬 节奏      更新时间:2023-09-26

我正在使用带有速度加载功能的余烬。

配速:http://github.hubspot.com/pace/docs/welcome/

在我的代码中,我在每条路线中重复此操作,以便出现加载栏:

App.IndexRoute = Ember.Route.extend({
  activate: function() {
    this._super();
    return Pace.restart();
  },
  deactivate: function() {
    this._super();
    return Pace.stop();
  }
});
App.AboutRoute = Ember.Route.extend({
    activate: function() {
    this._super();
    return Pace.restart();
  },
  deactivate: function() {
    this._super();
    return Pace.stop();
  }
});

有没有办法不在每个路由中重复代码?谢谢!

我建议创建一个Mixin或使用Ember的加载路线。

因此,在您的情况下,Mixin 将按如下方式工作:

App.PaceLoader = Ember.Route.extend({
  activate: function() {
    this._super();
    return Pace.restart();
  },
  deactivate: function() {
    this._super();
    return Pace.stop();
  }
});

然后只需将其包含在您希望它工作的每条路由中:

App.AboutRoute = Ember.Route.extend(App.PaceLoader, {
  //the rest of your route code here...
});

我以前没有使用过 Pace,但你可以把它添加到 Ember 不太明显的加载路线中(我不相信他们已经记录了它......),它在每个过渡中使用:

App.LoadingRoute = Ember.Route.extend({
  activate: function() {
    this._super();
    return Pace.restart();
  },
  deactivate: function() {
    this._super();
    return Pace.stop();
  }
});

如果这有效,则不必将其包含在任何其他路由中。 :)

您可以通过执行以下操作来覆盖所有路由:

Ember.Route.reopen({
  activatePace: function() {
    return Pace.restart();
  }.on('activate'),
  deactivatePace: function() {
    return Pace.stop();
  }.on('deactivate')
});

此外,这不会干扰现有的activate/deactivate钩子,因此您不必调用this._super()

在此处查看有关重新开放的文档