Nathan
Nathan

Reputation: 470

Changing Templates and Subscriptions with Select dropdown

Example: If I choose grapes, I would like to subscribe to the grapes collection, unsubscribe to all other collections and then render a new template. How do I listen for when a new option has been selected and act accordingly?

<select>
    <option value="choose fruit">
    <option value="grapes">
    <option value="strawberries">
</select>

Thanks!

Upvotes: 0

Views: 375

Answers (2)

user3374348
user3374348

Reputation: 4101

To elaborate on

If not then you can set a session variable and use a global autorun to start and stop your subscriptions.

to automatically unsubscribe and resubscribe when the session variable is changed, you can use a Deps.autorun:

Deps.autorun(function () {
    if (!isTheFruitsPage(Router.current())) return;
    var fruit = Session.get("selectedFruit");
    if (fruit === "grapes") {
        Meteor.subscribe("grapes");
    } else if (fruit === "strawberries") {
        Meteor.subscribe("strawberries");
    }
});

Each time the selectedFruit Session variable changes, or the current page changes, Meteor will unsubscribe from the previous subscriptions made by the autorun (if any) and then re-run the function. It's also smart enough to avoid unsubscribing and resubscribing for any subscription which doesn't change.

Upvotes: 0

David Weldon
David Weldon

Reputation: 64322

Let's say you had a template with a select element like this:

<template name="hello">
  <select class="fruit">
    <option value="grapes">grapes</option>
    <option value="strawberries">strawberries</option>
  </select>
</template>

Then you could add a change event which you could use to determine the route:

Template.hello.events({
  'change .fruit': function (event) {
    var value = $(event.target).val();
    var routeName = routeNameFromFruit(value);
    Router.go(routeName);
  }
});

I'm assuming you are using iron-router, so Router.go is available.

If you are using IR, you can manage your subscription changes with waitOn. If not then you can set a session variable and use a global autorun to start and stop your subscriptions.

Upvotes: 2

Related Questions