为什么铁路由器0.9.4数据在!ready()之后运行,然后在所有其他钩子之后再次运行?

时间:2014-11-09 06:04:45

标签: meteor iron-router

我在路由器配置中进行了一些调试,我注意到我的data回调在this.ready()返回true之前运行,然后再次运行,之后,例如,action!这看起来很奇怪,因为我可能需要数据来渲染我的模板。为什么data之前没有action运行?

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading'
});

/*
 * logged to console when navigating to 'home' route:
 *
 * 1. onRun
 * 2. waitOn
 * 3. onBeforeAction: not ready
 * 4. data: not ready
 *
 * ... 2 second delay (see sleep in publication)
 *
 * 5. onBeforeAction: ready
 * 6. action
 * 7. onAfterAction
 * 8. data: ready
 *
 * and, if you click the link to navigate away:
 *
 * 8. onStop
 */

Router.map(function() {
  this.route('home', {
    path: '/',
    onRun: function() {           // runs once (not after hot reload)
      console.log('onRun');
    },
    waitOn: function() {          // runs once
      console.log('waitOn');
      return [Meteor.subscribe('people')];
    },
    data: function() {            // runs multiple times
      if (this.ready()) {
        console.log('data: ready');
      } else {
        console.log('data: not ready');
      }
      return {
        'people': People.find()
      };
    },
    onBeforeAction: function() {  // runs multiple times
      if (this.ready()) {
        console.log('onBeforeAction: ready');
      } else {
        console.log('onBeforeAction: not ready');
      }
      // Will also run reactively. In other words,
      // if we called this.data().people.count(), our
      // onBeforeAction function would re-run more times,
      // because the cursor returned from People.find()
      // is a reactive data source.
    },
    action: function() {          // runs once
      console.log('action');
      this.render();
      // Will also run reactively.
    },
    onAfterAction: function() {   // runs once
      console.log('onAfterAction');
      // Will also run reactively.
    },
    onStop: function() {          // runs once if you navigate away
      console.log('onStop');
    }
  });

  return this.route('otherRoute', {
    path: '/otherRoute',
    template: 'home'
  });
});

Router.onBeforeAction('loading');

完整源代码:https://gitlab.com/meonkeys/meteor-iron-router-data-last

1 个答案:

答案 0 :(得分:0)

对于您的数据,请尝试这样做,因为现在,无论this.ready()是什么,您总是会返回数据

    data: function() {
       if (this.ready()) {
          console.log('data: ready');

          return { 'people': People.find() };

       } else {
          console.log('data: not ready');
       }
},