【问题标题】:How can I make Meteor subscriptions dynamic?如何使 Meteor 订阅动态化?
【发布时间】:2015-11-18 15:40:54
【问题描述】:

我希望让我的流星订阅动态/反应。现在,我有一个页面,它根据分配给它的模板 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 等于我选择的模板的选项值。谁有想法?我真的不知道从哪里开始...

谢谢!

【问题讨论】:

  • 您想要全局订阅还是模板级订阅? IE。导航到新路线/模板后是否应该停止订阅?
  • 嗨 - 我希望它是模板级别的订阅。

标签: dynamic meteor subscription


【解决方案1】:

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

  1. 创建一个范围为您的模板的反应变量。
  2. 在您的事件处理程序中更新 (1)。
  3. 结合使用template subscriptiontemplate 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

【讨论】:

  • 你是真正的救星!!
【解决方案2】:

要获取所选选项的 id,请使用 jQuery 选择器按 id 选择,然后选择该菜单的 .val()

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

【讨论】:

  • 明白了,我没有意识到我可以在模板帮助文件中使用订阅方法..
  • 我建议将它放在模板事件处理程序中,而不是在这种情况下作为帮助程序,因为您正在对菜单选择做出反应。
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 2018-04-08
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多