meteormeteor-blazemeteor-accountsmeteor-useraccounts

Meteor - event on {{if currentUser}} content loaded


I have a template

{{#if currentUser}}
    <input id="datetimepicker" type="text" >
{{/if}}

I want do add

$('#datetimepicker').datetimepicker();

But in methods of template:

content of {{#if currentUser}} is not accessible because collection with user is loaded after template. I can use setTimeout, but this is non stable solution. I can to type in template

{{#if currentUser}}
    <input id="datetimepicker" type="text" >
    <script>
        $('#datetimepicker').datetimepicker();
    </script>
{{/if}}

but this is not elegant.

How to catch rendering of content in block {{if currentUser}} in correct way? Or maybe should I not use this syntax generally and there is other manner of checking is user is loaded. If yes, link to proper tutorial please.


Solution

  • The way to do this is to make the content of the if another template, and then use the onRendered or onCreated methods of that template.

    {{#if currentUser}}
        {{> datePicker}}
    {{/if}}
    ...
    
    <template name="datePicker">
      <input id="datetimepicker" type="text" >
    </template>
    

    JS:

    Template.datePicker.onCreated(() => {
      // something
    });