Meteor的事件处理函数中的this:这是如何绑定到模型对象的



下面的代码取自tuttsplus中的教程。

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

这是模板:

<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>

我想知道this是如何绑定到模型对象产品的?这在我看来像魔术。

表达式"click .Product"指定具有类Product的HTML元素上的click事件应该触发指定的函数。我理解。但我不明白为什么this绑定到Products数组的一个元素。

这就是Handlebars(Meteor构建的基础)的工作方式。您在模板中看到的不是纯JS,而是特定于Handlebars的语法。

每个块辅助对象中,上下文是设置要迭代的数组的每个元素。因此,如果您使用InStock,它将在当前迭代的元素上查找它。

this关键字用于消除歧义。如果您有一个名为InStock的普通助手注册,这将派上用场,例如:

Template.Products.InStock = function (){
   //...
};

但是,您需要确保引用的是数组中元素的属性,因此可以使用this显式访问其上下文。

最新更新