【问题标题】:Iron-Router RouteController Inheritance: Why does the Parent Controller's Hook run before the Child's?Iron-Router RouteController 继承:为什么 Parent Controller 的 Hook 在 Child 之前运行?
【发布时间】:2014-09-10 12:25:55
【问题描述】:

我一直在为 Meteor (0.8.1.3) 使用出色的 Iron-Router 包 (0.7.1),并且遇到了一些似乎有点违反直觉的事情。我在下面提供了一个示例。

以下代码是在 Iron-Router 提供的 Tinytests 的上下文中编写的。 https://github.com/EventedMind/iron-router/blob/devel/test/both/route_controller.js

var Parent = RouteController.extend({
  onBeforeAction: function(pause) {
    console.log('I\'m in the parent!');
    pause();
  }
});

var Child = Parent.extend({
  onBeforeAction: function(pause) {
    console.log('I\'m in the child!');
    pause();
  }
});

var inst = new Child(Router, route, {});
inst.runHooks('onBeforeAction');

测试导致孩子打印出“我在父母中” 我原以为孩子会打印出“我在孩子里面”

我觉得在面向对象编程中,Child 的 onBeforeAction 覆盖 Parent 会更自然。

话虽如此,如果这是故意的,我怎么能颠覆钩子的顺序,只让孩子的 onBeforeAction 运行?

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    看起来是故意的:

    https://github.com/EventedMind/iron-router/blob/devel/lib/route_controller.js#L97

    // concatenate together hook arrays from the inheritance
    // heirarchy, starting at the top parent down to the child.
    var collectInheritedHooks = function (ctor) {
      var hooks = [];
    
      if (ctor.__super__)
        hooks = hooks.concat(collectInheritedHooks(ctor.__super__.constructor));
    
      return Utils.hasOwnProperty(ctor.prototype, hookName) ?
        hooks.concat(ctor.prototype[hookName]) : hooks;
    };
    

    如果您不希望父挂钩运行,看起来您将不得不跳过使用继承,而是将常用功能混合到各种控制器中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 2010-11-13
      • 1970-01-01
      相关资源
      最近更新 更多