Meteor-在匿名函数中使用反应变量

Meteor-在匿名函数中使用反应变量,meteor,Meteor,如何在模板呈现函数中的匿名函数中使用被动模板变量(来自template.data)?(我想让它保持反应性)。 不确定您到底想做什么(比如打印this.data.title,无论何时更改),但您应该: 使用(添加ReactiveVar包,然后创建var myVar=newreactivevar() 如有必要,使用(或在模板创建/渲染事件中)包装函数 所以你可以说: 父模板HTML: {{>templateName title=myReactiveVar} 父模板JS: Template.pa

如何在模板呈现函数中的匿名函数中使用被动模板变量(来自template.data)?(我想让它保持反应性)。


不确定您到底想做什么(比如打印
this.data.title
,无论何时更改),但您应该:

  • 使用(添加
    ReactiveVar
    包,然后创建
    var myVar=newreactivevar()
  • 如有必要,使用(或在模板创建/渲染事件中)包装函数
  • 所以你可以说:

    父模板HTML:

    
    {{>templateName title=myReactiveVar}
    
    父模板JS:

    Template.parentTemplateName.helpers({
    myReactiveVar:函数(){
    返回新的ReactiveVar(“我的标题!”);
    }
    });
    
    模板JS:

    Template.templateName.onRendered(函数(){
    //每当功能块中的ReactiveVar发生更改时重新运行。
    这是一个自动运行(函数(){
    //打印与当前模板关联的字段“标题”
    log(getValue(this.data.title));
    });
    });
    函数getValue(变量){
    return(变量instanceof ReactiveVar)?variable.get():variable;
    }
    
    对我来说,使用autorun()和Template.currentData()从autorun()中获取值非常简单:


    问题是onRender函数中的匿名函数中的变量可用。我正在尝试在匿名函数中使用Template.data中的title字段,并使其保持反应性。我不需要在页面上打印它,因此不需要帮助。现在更新我的问题以使其更清楚。谢谢!您知道数据context(即
    template.data
    )默认为。这就是为什么我在上面说明您必须显式使用
    ReactiveVar
    。这就是为什么我使用了一个助手,但只是调用它。您可以随意创建数据上下文。仅供参考,在自动运行中使用“this”似乎并没有引用模板。我必须使用template.currentData()从自动运行中获取数据。@jetlej感谢您的反馈,事实上我忽略了这一部分,因为它只是对您的代码进行了修改。不过,我不确定下次我是否会花费精力来帮助您。
    Template.templateName.rendered = function() {
        function testFunction(){
            //Log the field 'title' associated with the current template
            console.log(this.data.title);
        }
    });
    
    Template.templateName.onRendered(function(){
       console.log(this.data.title);
    });
    
    let title;
    
    Template.templateName.rendered = function() {
       this.autorun(function(){
            title = Template.currentData().title;
       });
    
        function testFunction(){
            console.log(title);
        }
    });