问题
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!
回答1:
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:
- Scoped Reactivity
- Template Subscriptions
- Changing Templates and Subscriptions with Select dropdown
回答2:
To get the id of the selected option use a jQuery selector to select by id then select .val()
of that menu:
var templateId = $('select[id="templateSelect"]').val();
Meteor.subscribe('templates', templateId);
来源:https://stackoverflow.com/questions/32195460/how-can-i-make-meteor-subscriptions-dynamic