如何使 Meteor 订阅动态化?

How can I make Meteor subscriptions dynamic?

我想订阅流星 dynamic/reactive。现在,我有一个页面,它根据分配给它的模板 ID 订阅模板集合:

Meteor.subscribe('templates', templateId)

在同一页面上,我有一个模板名称和 ID 的下拉列表:

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

我希望订阅变量 templateId 等于我 select 的模板的选项值。谁有想法?我真的不知道从哪里开始...

谢谢!

要获得 selected 选项的 id 使用 jQuery select 或 select by id 然后该菜单的 select .val()

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

如果你想要模板订阅,你应该遵循这个策略:

  1. 创建一个作用域为您的模板的反应变量。
  2. 在您的事件处理程序中更新 (1)。
  3. 使用 template subscription combined with a template autorun - 这将确保您只有一个未完成的订阅,并且会在模板被销毁时自动清理订阅。
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());
  });
});

推荐阅读:

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