Diogenes
Diogenes

Reputation: 2757

How do you conditionally subscribe to data on the front end in meteor?

I know how to conditionally publish data in meteor, but how do you conditionally subscribe? I'm thinking of the case where you have an application with separate pages (using meteor-router, for example) and you only need certain subscriptions on certain pages.

Upvotes: 2

Views: 820

Answers (2)

Tarang
Tarang

Reputation: 75945

You could also do a multi collection publish/subscription depending on the page. As the page changes the subscription is automatically changed depending on what the page is:

client side js

Deps.autorun(function() {
    Meteor.subscribe("page_subscriptions", Meteor.Router.page());
});

server side js

Meteor.publish("page_subscriptions", function(page) {
    if(page=="home") {
        return [
                Collection1.find({}),
                Collection2.find({}),
                Collection3.find({})
        ];
    }else if(page=="about") {
        return [
                Collection3.find({}),
                Collection4.find({})
        ];
    }
});

So each page has its own set of collections which can have individualized queries, while using the same subscription.

Because Meteor.Router.page() is reactive, as soon as you route to a different page the subscription will be changed.

Upvotes: 1

BenjaminRH
BenjaminRH

Reputation: 12172

Use if statements in a Deps.autorun() method. The if statements should test against Session variables, which will make it reactive, triggering Deps.autorun to change the subscriptions when the conditions change. Thus:

Deps.autorun(function() {
    sub.stop(); // Stop the previous subscription, because it's changed.
    if (Session.equals('page', 'foo')) {
        sub = Meteor.subscribe('bar');
    } else if (Session.equals('page', 'lorem')) {
        sub = Meteor.subscribe('ipsum');
    }
    // etc.
});

Upvotes: 2

Related Questions