[英]this in event handling functions of Meteor: How does this get bound to model object?
The following code is taken from a tutorial in tutsplus. 以下代码取自tutsplus中的教程 。
if (Meteor.isClient) {
var Products = new Array(
{ Name: "Screw Driver",
Price: "1.50",
InStock: true},
{ Name: "Hammer",
Price: "2.50",
InStock: false}
);
Template.Products.ProductArr = function () {
return Products;
};
Template.Products.events = {
"click .Product": function () {
if (this.InStock)
confirm("Would you like to buy a " + this.Name + " for " + this.Price + "$");
else
alert("That item is not in stock");
}
};
}
Here is the template: 这是模板:
<template name="Products">
{{#each ProductArr}}
<div class="Product">
<h2>{{Name}}</h2>
<p>Price: ${{Price}}</p>
{{#if this.InStock}}
<p>This is in stock</p>
{{else}}
<p>This is sold out</p>
{{/if}}
</div>
{{/each}}
</template>
I wonder how this
get bound to the model object product? 我不知道
this
如何绑定到模型对象产品? This looks like magic to me. 在我看来,这就像魔术。
The expression "click .Product"
specifies that the click
event on HTML elements having class Product
should trigger the specified function. 表达式
"click .Product"
指定具有类Product
HTML元素上的click
事件应触发指定的函数。 I understand it. 我明白。 But I don't understand why
this
is bound to an element of the Products
array. 但是我不明白为什么
this
它绑定到Products
数组的元素。
This is how Handlebars (which Meteor builds on) works. 这就是(流星所构建的)车把的工作方式。 What you're seeing in the template isn't pure JS, but syntax specific to Handlebars.
您在模板中看到的不是纯JS,而是特定于Handlebars的语法。
Inside the each block helper, the context is to set each element of the array you're iterating over. 在每个块帮助器中,上下文用于设置要迭代的数组的每个元素。 So if you use InStock , it will look for it on the element of the current iteration.
因此,如果使用InStock ,它将在当前迭代的元素上寻找它。
The this keyword is used for disambiguation. 此关键字用于消除歧义。 This comes in handy if you have a general helper registered with the name InStock , like this, for example:
如果您有一个名为InStock的通用帮助程序,则这样会很方便,例如:
Template.Products.InStock = function (){
//...
};
But you want to make sure you're referring to the property of the element from the array, so you can use this to access its context explicitly. 但是你要确保你指的是从数组元素的属性,所以你可以用它来显式访问它的上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.