2017-08-01 41 views
1

此Meteor代碼允許用戶從下拉選項列表中進行選擇,並使用所選值來訂閱集合並返回要顯示的文檔。
訂閱速度不夠快,因此在執行myCol.findOne({person: fName})時出現未定義。模板事件在收集之前等待訂閱。查找

任何想法如何解決它? THX

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> 

回答

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>