Trung Tran
Trung Tran

Reputation: 13771

How can I make Meteor subscriptions dynamic?

I am looking to make my meteor subscriptions dynamic/reactive. Right now, I have a page that subscribes to a collection of templates based on a template ID that is assed to it:

Meteor.subscribe('templates', templateId)

On the same page, I have a dropdown list of template names and ID's:

    <p><label>Select Template</label></p>
    <select id="templateSelect" name="templateSelect">
        <option disabled selected> Select Template </option>
        {{#each orderTemplates}}
            <option value="{{this._id}}">{{this.templateName}}</option>
        {{/each}}
    </select>

I want the subscription variable templateId to be equal to the option value of the template that I select. Anyone have any ideas? I'm really not sure where to begin with this one...

Thanks!

Upvotes: 3

Views: 1378

Answers (2)

David Weldon
David Weldon

Reputation: 64342

If you want a template subscription, you should follow this strategy:

  1. Create a reactive variable scoped to your template.
  2. Update (1) in your event handler.
  3. Use a template subscription combined with a template autorun - this will ensure you have only one outstanding subscription and will automatically clean up the subscriptions when the template is destroyed.
Template.myTemplate.events({
  'change #templateSelect': function (event, template) {
    // extract the value/id from the selected option
    var value = $(event.target).val();

    // update the templateId - whis will cause the autorun to execute again
    template.templateId.set(value);
  }
});


Template.myTemplate.onCreated(function() {
  var self = this;

  // store the currently selected template id as a reactive variable
  var templateId = new ReactiveVar;

  // this will rerun whenever templateId changes
  this.autorun(function() {
    // Subscribe for the current templateId (only if one is selected). Note this
    // will automatically clean up any previously subscribed data and it will
    // also stop all subscriptions when this template is destroyed.
    if (templateId.get())
      self.subscribe('orderTemplateShow', templateId.get());
  });
});

Recommended reading:

  1. Scoped Reactivity
  2. Template Subscriptions
  3. Changing Templates and Subscriptions with Select dropdown

Upvotes: 4

Michel Floyd
Michel Floyd

Reputation: 20256

To get the id of the selected option use a jQuery selector to select by id then select .val() of that menu:

var templateId = $('select[id="templateSelect"]').val();
Meteor.subscribe('templates', templateId);

Upvotes: 2

Related Questions