【问题标题】:template event to wait for subscription before collection.find在collection.find之前等待订阅的模板事件
【发布时间】:2017-08-01 07:32:18
【问题描述】:

此 Meteor 代码允许用户从下拉选项列表中进行选择,并使用选择的值订阅集合并返回要显示的文档。
订阅速度不够快,因此在执行myCol.findOne({person: fName}) 时出现未定义。

知道如何解决吗?谢谢

Template.manualSearch.events({
  'change select': function () {
  let name = $("#fName option:selected").html().toLowerCase();
    dict.set('person', fName);
    Meteor.subscribe('myCol', dict.get('person'));
    let personDoc = myCol.findOne({person: fName});
    if (personDoc) { // <=== always undefind
      let info = JSON.stringify(personDoc);
      document.getElementById('debug').innerHTML = info;
    }  
  }
});
<template name="manualSearch">
  <select name="nmnm" id="fName">
    {{#if Template.subscriptionsReady}}
      {{#each fNames}}
        <option>{{this.fName}}</option>
      {{/each}}
    {{/if}}
  </select>

  <p id="debug"></p>
</template>

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    订阅一个事件真的是个坏主意。这样您就可以在订阅后打开订阅,而无需清理它们。您应该将订阅移动到 onCreated 回调中,然后使用像 SessionReactiveVar 这样的反应变量来更新订阅。这样,Meteor 负责订阅生命周期。您的返回值应该进入帮助程序。

    // js
    Template.manualSearch.onCreated(function() {
      Session.setDefault('person', 'some-default-name');
      this.autorun(() => {
        this.subscribe('myCol', Session.get('person'));
      });
    });
    
    Template.manualSearch.helpers({
      info() {
        const person = myCol.findOne({ person: Session.get('person') });
        if (person) {
          return JSON.stringify(person);
        }
        return null;
      }
    });
    
    Template.manualSearch.events({
      'change select'() {
        Session.set('person', $("#fName option:selected").html().toLowerCase());
      }
    });
    
    
    // html
    <template name="manualSearch">
      ...
      <p id="debug">{{info}}</p>
    </template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2018-09-05
      • 2021-05-06
      • 1970-01-01
      相关资源
      最近更新 更多