2014-06-08 65 views
1

我正在通过Discover Meteor工作,并且遇到了一些我不太清楚的代码。这里是我的模板和相关的JS流星模板中的“this”关键字

<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”是我们正在执行的函数的“所有者”,或者更确切地说,函数是每个the quirksmode article的方法的对象,但我并不真正了解这个链如何流星正在实施它。只看代码,我希望this.userId为null。有人可以帮我或指点我的一些文件,解释“这”在Meteor中的工作原理吗?

回答

4

我很惊讶这个问题没有被更多地询问,因为它并不明显,也没有明确记录。

推荐阅读:

上述条款应说明情况很清楚,但这里的快速版本:

上下文( “本” )在助手内部是模板实例的上下文。您可以直接给模板的背景是这样的:

{{> 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}} 
+0

感谢大卫。这澄清了相当大的事情,但就这一特定情况而言,我仍有点困惑。 userId将源自通过陨石账户包登录的用户。我没有看到我们设置数据上下文的任何地方。如果有什么我希望数据上下文被设置为帖子而不是用户。我可以忽略一些东西吗 –

+0

书中的这一章是哪一章? –

+0

承诺8-1,第91页 –