此 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>
订阅活动确实是一个坏主意。这样,您就可以在订阅后打开订阅,而无需清理它们。应将订阅移动到onCreated
回调中,然后使用反应式 var(如Session
或ReactiveVar
(来更新订阅。这样,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>