Javascript 用于meteor.js 的模板加载事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11167390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Template onload event for meteor.js
提问by Gezim
I know meteor exposes events such as "click", for DOM element but I'm wondering if there's a load event that's fired when a template or partial is loaded? How would I accomplish this?
我知道meteor 会为DOM 元素公开诸如“click”之类的事件,但我想知道在加载模板或部分时是否会触发加载事件?我将如何做到这一点?
Thanks.
谢谢。
回答by Joscha
For Meteor starting from 0.4.0 preview, you can use Template.myTemplate.created
.
对于从 0.4.0 预览版开始的 Meteor,您可以使用Template.myTemplate.created
.
In Template.myTemplate.created
the DOM is not ready however.
然而Template.myTemplate.created
在 DOM 中还没有准备好。
If you need to manipulate the DOM, you might want to use Template.myTemplate.rendered
instead and use a boolean value to track the state within the Template object like this:
如果您需要操作 DOM,您可能希望改为使用Template.myTemplate.rendered
布尔值来跟踪 Template 对象中的状态,如下所示:
Template.myTemplate.rendered = function() {
if(!this._rendered) {
this._rendered = true;
console.log('Template onLoad');
}
}
回答by Nachiket
Following should work.
Meteor.defer will get called once template is added to DOM and rendered.
以下应该有效。
一旦模板被添加到 DOM 并呈现,Meteor.defer 将被调用。
<template name="temp">
//regular stuff
{{invokeAfterLoad}}
</template>
Template.temp.invokeAfterLoad = function () {
Meteor.defer(function () {
$('mydiv').jquerify();
});
return "";
};
回答by Mike Bannister
I'd recommend this rather than the accepted answer, slightly less gross IMHO:
我会推荐这个而不是接受的答案,恕我直言略少:
<template name="temp">
{{aReactiveHelper}}
</template>
Template.temp.aReactiveHelper = function() {
var someValue = Session.get('someValue');
invokeAfterLoad();
return someValue;
};
var invokeAfterLoad = function () {
Meteor.defer(function () {
$('mydiv').doSomething();
});
};
The assumption is that you want to invoke something after the template loads because it's reacting to a reactive object.
假设您想在模板加载后调用某些东西,因为它正在对反应式对象做出反应。
The benefit here is you're not adding animation code to your template.
这里的好处是您不会向模板添加动画代码。