2014-06-08 63 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頁 –