2

As far as I can tell, when I suscribe to a result set inside an iron-router hook, like before: or waitOn:, it works fine, but it seems to get torn down, as soon as another route runs. Does anyone know if this is what happens?

Assuming it is, does that mean that only way to make a subscription persist across routes is to subscribe somewhere OTHER than the Router.map() function?

4

2 回答 2

7

如果要保持路由之间的订阅,则必须重新订阅。实现此目的的一种简单方法是使用Controllers。还值得一提的是,Iron-Router/Meteor 足够聪明,可以知道您何时在路由之间重复使用相同的订阅,因此它们不会再次加载。

一种方法可以做到:

ProjectController = RouteController.extend({
    before: [
        function() {
            this.subscribe("project.comments", this.params.projectId).wait();
            this.subscribe("project.log", this.params.projectId).wait();
        }
    ]
});

Router.map(function () {
  this.route('project.overview', {
    path: '/project/:projectId/overview',
    controller: 'ProjectController'
  });

  this.route('project.tasks', {
    path: '/project/:projectId/tasks',
    controller: 'ProjectController'
  });
});

现在“project.overview”和“project.tasks”路由将订阅“project.comments”和“project.log”。

然后,您可以制作一个特定于路由的控制器并从“ProjectController”扩展以进行特定于路由的订阅:

ProjectController = RouteController.extend({
    before: [
        function() {
            this.subscribe("project.comments", this.params.projectId).wait();
            this.subscribe("project.log", this.params.projectId).wait();
        }
    ]
});

ProjectOverviewController = ProjectController.extend({
    before: [
        function() {
            this.subscribe("project.stats", this.params.projectId).wait();
        }
    ]
});

Router.map(function () {
  this.route('project.overview', {
    path: '/project/:projectId/overview',
    controller: 'ProjectOverviewController'
  });

  this.route('project.tasks', {
    path: '/project/:projectId/tasks',
    controller: 'ProjectController'
  });
});

“project.overview”路由现在将订阅“project.comments”、“project.log”和“project.stats”。

如果您需要应用程序范围的订阅,另一种方法是使用“Router.before”挂钩(https://github.com/EventedMind/iron-router#using-hooks):

Router.before(function() {
    this.subscribe("global.sub");
});
于 2014-01-13T22:51:31.917 回答
4

您可以为所有路由定义订阅Router.configure

Router.configure({
    waitOn: function() { 
        return Meteor.subscribe('my-subscription');
    }
});
于 2014-01-13T22:36:16.280 回答