如何在模板渲染函数中的匿名函数中使用反应模板变量(来自Template.data)? (我想让它保持反应)。
Template.templateName.rendered = function() {
function testFunction(){
//Log the field 'title' associated with the current template
console.log(this.data.title);
}
});
答案 0 :(得分:0)
不确定您要做什么(比如打印this.data.title
何时更改?),但您应该:
reactive-var
包,然后创建var myVar = new ReactiveVar()
Tracker.autorun
(或this.autorun
)包裹您的函数。所以你可以这样:
父模板HTML:
<template name="parentTemplateName">
{{> templateName title=myReactiveVar}}
</template>
父模板JS:
Template.parentTemplateName.helpers({
myReactiveVar: function () {
return new ReactiveVar("My Title!");
}
});
模板JS:
Template.templateName.onRendered(function() {
// Re-run whenever a ReactiveVar in the function block changes.
this.autorun(function () {
//Print the field 'title' associated with the current template
console.log(getValue(this.data.title));
});
});
function getValue(variable) {
return (variable instanceof ReactiveVar) ? variable.get() : variable;
}
答案 1 :(得分:0)
对我来说很简单,使用autorun()并使用Template.currentData()从autorun()中获取值:
let title;
Template.templateName.rendered = function() {
this.autorun(function(){
title = Template.currentData().title;
});
function testFunction(){
console.log(title);
}
});
答案 2 :(得分:-1)
Template.templateName.onRendered(function(){
console.log(this.data.title);
});