簡體   English   中英

這在Meteor的事件處理功能中:這如何綁定到模型對象?

[英]this in event handling functions of Meteor: How does this get bound to model object?

以下代碼取自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");
        }
    };
}

這是模板:

<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數組的元素。

這就是(流星所構建的)車把的工作方式。 您在模板中看到的不是純JS,而是特定於Handlebars的語法。

每個塊幫助器中,上下文用於設置要迭代的數組的每個元素。 因此,如果使用InStock ,它將在當前迭代的元素上尋找它。

關鍵字用於消除歧義。 如果您有一個名為InStock的通用幫助程序,則這樣會很方便,例如:

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

但是你要確保你指的是從數組元素的屬性,所以你可以用來顯式訪問它的上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM