【问题标题】:What is a true equivalent of `window.onload` for an iron router route in a Meteor.js app?对于 Meteor.js 应用程序中的铁路由路由,真正相当于“window.onload”的是什么?
【发布时间】:2015-10-26 03:25:26
【问题描述】:

我有这样定义的铁路线(注意onAfterActioninitProfileComponent

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})};
    }
});

函数initProfileComponent希望使用由meteor/mustache发布机制创建的document.querySelectorAll元素找到,这就是为什么在onAfterAction中调用,但显然它不起作用,因为当它被调用时尚未渲染。

模板是这样定义的:

<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>

除了onAfterAction 为我的用例执行“buritos”之外,在哪里/如何定义一个回调以确保模板完全呈现。或者,我应该订阅什么?

【问题讨论】:

    标签: javascript meteor iron-router


    【解决方案1】:

    理想情况下,这应该在您的模板中完成。在 Meteor 中,所有模板都有 onCreatedonRendered 回调。如果你使用 onRendered,你可以确定所有的 DOM 元素都已经存在了。

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

    像这样初始化您的模板是个好习惯。使用 Iron Router 参数化您的模板,正如您已经在做的那样。

    【讨论】:

    • 我不使用 jQuery,但感谢您指出这一点,要了解,每次更新都会调用这个 onRendered 回调多少次...?意思是如果我在一个元素上初始化了一个小部件,我应该关注过度初始化还是旧引用是以前的元素未设置?
    • Meteor 默认自带 jQuery,所以你可以使用它。 onRendered 总是在第一次渲染模板实例时调用一次。请参阅文档:docs.meteor.com/#/full/template_onRendered
    猜你喜欢
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2015-08-11
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多