问题
I want to solve the following problem in Meteor.js:
I have a HTML element that appears in a template only if the user is logged in:
{{#if currentUser}} <input ...> {{/if}}. After the HTML element appears I need to execute a JS command on it. Thus I need some kind of callback that happens after the Template is updated. How to achieve this?
None of the reactive data sources I know of do the trick in this case as for example the Meteor.user() source triggers dependencies before the Template is updated. Also see my prior question here.
回答1:
Refactor your template code to put the content of the {{#if}} block helper inside a child template, that will get it's own onRendered life cycle event triggered only when both the condition is met, and the new HTML content implied is inserted in the DOM.
HTML
<template name="parentTemplate>
{{#if currentUser}}
{{> childTemplate}}
{{/if}}
</template>
<template name="childTemplate">
{{! whatever}}
</template>
JS
Template.childTemplate.onRendered(function(){
// here you go
});
回答2:
I would add needed code into autorun.
Template.mytemplate.onRendered(function() {
Tracker.autorun(function() {
user = Meteor.user()
if (user) {
// Your code here
}
}
}
来源:https://stackoverflow.com/questions/29722721/meteor-reactive-function-for-template-updates