Meteor Template帮助器中的"this"对象是什么?

Jam*_*ton 1 templates meteor

当Blaze调用Template.xxx.helper中定义的函数时,它会传递一个或多个参数.第一个参数是一个看似空的对象.它是什么?它可以用于什么?

以下是如何使用终端窗口重新创建我的准系统测试:

meteor create test
cd test
cat > test.html << EOF
<body>
  {{> test}}
</body>

<template name="test">
  <p>{{test1 "data"}}</p>
  <p>{{test2 key="value"}}</p>
</template>
EOF
cat > test.js << EOF
if (Meteor.isClient) {
  Template.test.helpers({
    test1: function (argument) {
      console.log(this, argument)
      return "test1 helper: " + argument
    }
  , test2: function (argument) {
      console.log(this, argument)
      return "test2 helper: " + argument.hash.key
    }
  });
}
EOF
meteor run
Run Code Online (Sandbox Code Playgroud)

这是扩展哈希对象后我在浏览器控制台中看到的内容:

Object {} "data"
Object {} S…s.kw {hash: Object}
  hash: Object
    key: "value"
  __proto__: Object__proto__: Spacebars.kw
Run Code Online (Sandbox Code Playgroud)

什么是this Object {}?特别是,有没有办法可以用它来发现哪个HTML元素触发了调用?

Jer*_* S. 5

在模板助手中,this是模板实例的数据上下文.

在您的示例中,未设置数据上下文,因此它返回一个空对象.但情况并非总是如此.想象一下以下示例:

<template name='parent'>
  {{#with currentUser}}
    {{> child}}
  {{/with}}
</template>
Run Code Online (Sandbox Code Playgroud)

在这种情况下Meteor.user()已经被设置为用于实例的数据上下文Template.child,所以Meteor.user()必然要this在Template.child.helpers().这允许您执行以下操作:

Template.child.helpers({
  greeting: function(){
    console.log(this); // logs Meteor.user() || undefined
    return 'Welcome back ' + this.username;
  }
});
Run Code Online (Sandbox Code Playgroud)

可以通过each或with阻止或通过父模板上下文显式设置数据上下文.如上例所示,您通常希望undefined在使用this帮助器时进行检查.

您的问题的简短答案是否this在模板助手中可以识别调用它的DOM节点是否定的.您可以通过原型(我没有检查过)从帮助器的参数中挖掘它,但我认为这是一个反模式.如果您关心帮助程序的来源,只需包含一个参数即可.继续前面的例子:

<template name='child'>
  <p>{{greeting}}</p>
  <p>{{greeting 'special'}}</p>
</template>
Run Code Online (Sandbox Code Playgroud)

和:

Template.child.helpers({
  greeting: function(str){
    if (str === 'special'){
      return 'Welcome to first class Ambassador ' + this.username;
    }
    return 'Please take your seat in coach ' + this.username;
  }
});
Run Code Online (Sandbox Code Playgroud)