Meteor reactive function for Template updates

跟風遠走 提交于 2019-12-22 10:59:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!