0

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!

Nathan
  • 470
  • 2
  • 5
  • 15

2 Answers2

2

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.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • I am using Iron Router, although I did not quite make it clear what I want. I do not want to render a new page per se, I want to replace a template within the page with a new template(a partial, as some call them). Thanks! – Nathan May 13 '14 at 18:26
  • 1
    Okay, then in your `event` callback set a session variable based on the selected value. Add a helper to the template which returns the value of the session variable. Finally, add `{{#if}}` and `{{else}}` conditionals to the template to show the correct sub-template. Does that make sense or do you need to see a full example? – David Weldon May 13 '14 at 18:51
  • No, that makes perfect sense. Thanks again! – Nathan May 13 '14 at 18:57
0

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.

user3374348
  • 4,101
  • 15
  • 29