How can I make Meteor subscriptions dynamic?

依然范特西╮ 提交于 2019-12-12 09:54:07

问题


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!


回答1:


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



回答2:


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);


来源:https://stackoverflow.com/questions/32195460/how-can-i-make-meteor-subscriptions-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!