如何使流星订阅动态? [英] How can I make Meteor subscriptions dynamic?
问题描述
Meteor.subscribe('templates',templateId)
在同一页面上,我有一个模板名称和ID的下拉列表:
code>< p>< label>选择模板< / label>< / p>
< select id =templateSelectname =templateSelect>
<选项已禁用选定>选择模板< / option>
{{#each orderTemplates}}
< option value ={{this._id}}> {{this.templateName}}< / option>
{{/ each}}
< / select>
我想要订阅变量 templateId
等于我选择的模板的选项值。任何人都有什么想法?我真的不知道从哪里开始...
谢谢!
如果您需要模板订阅,您应该遵循以下策略:
Template.myTemplate.events({
'change #templateSelect':function(event,template){
// extract所选项目的值/ id
var value = $(event.target).val();
//更新templateId - 这将导致自动运行再次执行
template.templateId.set(value);
}
});
Template.myTemplate.onCreated(function(){
var self = this;
//将当前选定的模板ID存储为反应变量
var templateId = new ReactiveVar;
//每当templateId更改时,这将重新运行
this.autorun(function(){
//订阅当前的templateId (只有当被选中)注意这个
//会自动清除任何以前订阅的数据,并且
//也可以在这个模板被销毁时停止所有的订阅
if(templateId .get())
self.subscribe('orderTemplateShow',templateId.get());
});
});
推荐阅读:
I am looking to make my meteor subscriptions dynamic/reactive. Right now, I have a page that subscribes to a collection of templates based on a template ID that is assed to it:
Meteor.subscribe('templates', templateId)
On the same page, I have a dropdown list of template names and ID's:
<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>
I want the subscription variable templateId
to be equal to the option value of the template that I select. Anyone have any ideas? I'm really not sure where to begin with this one...
Thanks!
If you want a template subscription, you should follow this strategy:
- Create a reactive variable scoped to your template.
- Update (1) in your event handler.
- Use a template subscription combined with a template autorun - this will ensure you have only one outstanding subscription and will automatically clean up the subscriptions when the template is destroyed.
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());
});
});
Recommended reading:
这篇关于如何使流星订阅动态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!