gpt4 book ai didi

templates - Meteor 模板助手中的 "this"对象是什么?

转载 作者:行者123 更新时间:2023-12-02 04:17:42 25 4
gpt4 key购买 nike

当 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

什么是this对象{}?特别是,有没有一种方法可以使用它来发现哪个 HTML 元素触发了调用?

最佳答案

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

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

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

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

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

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

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

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

关于templates - Meteor 模板助手中的 "this"对象是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678897/

25 4 0