Search code examples
meteoriron-router

Iron Router: How to Provide Same Data to Multiple Routes


It's evident how to provide route-specific data, i.e. through the use of a controller:

PostController = RouteController.extend({
  layoutTemplate: 'PostLayout',
  template: 'Post',
  waitOn: function () { return Meteor.subscribe('post', this.params._id); },
  data: function () { return Posts.findOne({_id: this.params._id}) },
  action: function () {
    this.render();
  }
});

But how does one provide data for the application in general? In the case that every route needs to be subscribed to the same subset of information, so that the pub/sub doesn't need to be re-done on every route change. Thanks!


Solution

  • It sounds to me like you are looking for a completely general publication/subscription scheme so that you do not have to define the waitOn/data option combination for every single route or route controller that you define. In that case, you can simply publish a given set of data on the server like so:

        Meteor.publish('someData', function() {
            return SomeDataCollection.find({});
        });
    

    and subscribe to that set of data on the client like so:

        Meteor.subscribe('someData');
    

    With this publication/subscription pair setup, you will have access to the data provided in all routes. You just have to make sure that you check for non-existent data in your code to handle the first load of any given template when the data has not been loaded on the client yet. In this manner, you would never have to actually define a the waitOn and data options for any route or route controller.

    If you would like to utilize Iron Router in a different way than through route controllers, you also have the option of waiting on one/many subscriptions globally by using the Router.configure({}); function. To use the example above:

        Router.configure({
            waitOn: function() {
                return Meteor.subscribe('someData');
            }
        });
    

    For information about this route option and all of the other options that you have available at a global level, check this out.