简体   繁体   中英

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.

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 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. I understand it. But I don't understand why this is bound to an element of the Products array.

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.

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM