简体   繁体   中英

What is a true equivalent of `window.onload` for an iron router route in a Meteor.js app?

I have an iron route defined like this (pay attention to onAfterAction and initProfileComponent )

var initProfileComponent = function () {
    var elements = document.querySelectorAll('.sliderComponent');
    //... do stuff and decorate the elements
}

Router.route('newProfile', {
    path: '/new-profile/:_id',
    onAfterAction: function () {
        initProfileComponent();

    },
    data: function () {
        return {profile: Profile.findOne({_id: this.params._id})};
    }
});

The function initProfileComponent wishes to find using document.querySelectorAll elements created by meteor/mustache publish mechanism, that is why is called in onAfterAction , but obviously it doesn't work, since, when it is called the elements are not yet rendered.

The templates are defined like this :

<template name="newProfile">
    <div class="main-title new-profile">
        new profile
    </div>
    {{#each profile.properties}}
        {{> sliderComponent}}
    {{/each}}
</template>

<template name="sliderComponent">
    <div class="sliderComponent dragdealer">
        <div class="handle">{{label}}</div>
    </div>
</template>

Other than onAfterAction which does "buritos" for my use case, where/how can one define an callback that ensures that the template was fully rendered. Or, to what should I subscribe?

Ideally this should be done in your template. In Meteor all templates have onCreated and onRendered callbacks. If you use onRendered, you can be sure that all DOM elements are already there.

Template.sliderComponent.onRendered(function(){
    var elements = $('.sliderComponent');
    //... do stuff and decorate the elements
});

It is good practice to initialize your template like this. Use Iron Router to parameterize your templates, as you are already doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM