meteor模板中的“this”关键字

我正在通过Discover Meteor工作,并且遇到了一些我不太清楚的代码。 这是我的模板和相关的JS

<template name="postItem"> <div class="post"> <div class="post-content"> <h3><a href="{{url}}">{{title}}</a><span>{{domain}}</span></h3> <p> submitted by {{author}} {{#if ownPost}}<a href="{{postEditPath this}}">Edit</a>{{/if}} </p> </div> <a href="{{postPagePath this}}" class="discuss btn">Discuss</a> </div> </template> Template.postItem.helpers({ ownPost: function(){ return this.userId == Meteor.userId(); }, domain: function() { var a = document.createElement('a'); a.href = this.url; return a.hostname; } }); 

总的来说,我不太清楚“这个”是如何在这个js的背景下工作的。 我理解“this”是我们正在执行的函数的“所有者”,或者更确切地说,函数是quirksmode文章中的一个方法,但是我并不真正理解这个链。meteor如何实现它。 只看代码,我期望this.userId为空。 有人可以帮助我,或者指出一些解释“this”在Meteor中的作用的文档吗?

我很惊讶这个问题不是经常被问到,因为这个问题不明显,也没有明确的logging。

推荐阅读:

  • meteor模板和数据上下文
  • 文档的实时模板部分

上面的文章应该很清楚地说明情况,但是这里是快速的版本:

帮助器内的上下文(“this”)是模板实例的上下文。 您可以直接给模板一个上下文,如下所示:

 {{> postItem myItem}} // The context is now myItem. "this" inside of a helper is the myItem document. 

或者间接如此:

 {{#each posts}} // The context is now a post. "this" inside of a helper is a post document. {{/each}}