【问题标题】:What is the "this" object inside a Meteor Template helper?Meteor 模板助手中的“this”对象是什么?
【发布时间】:2015-12-17 04:33:03
【问题描述】:

当 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

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

Object {} "data"
Object {} S…s.kw {hash: Object}
  hash: Object
    key: "value"
  __proto__: Object__proto__: Spacebars.kw

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

【问题讨论】:

标签: templates meteor


【解决方案1】:

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

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

<template name='parent'>
  {{#with currentUser}}
    {{> child}}
  {{/with}}
</template>

在这种情况下,Meteor.user() 已设置为Template.child 实例的数据上下文,因此Meteor.user() 绑定到Template.child.helpers() 中的this。它允许您执行以下操作:

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

可以通过eachwith 块或通过父模板上下文显式设置数据上下文。如上例所示,在帮助程序中使用 this 时,您通常需要检查 undefined

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

<template name='child'>
  <p>{{greeting}}</p>
  <p>{{greeting 'special'}}</p>
</template>

还有:

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

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多