2016-09-23 90 views
0

試圖更好地理解數據上下文如何在Meteor中工作,因爲我無法弄清楚我面臨的這個問題。沒有在任何地方找到明確的答案。我有以下模板模板vs幫助器中的流星數據上下文

<template name="list"> 
    {{#each listItem}} 
    {{> listItemDetail}} 
    {{/each}} 
</template> 

<template name="listItemDetail"> 
    <p>{{_id}} {{title}}</p> 
    <p>{{idViaHelper}}</p> 
</template> 

而且在我的JavaScript我有

Template.list.helpers({ 
    'listItem':() => { 
     return List.find().fetch(); 
}) 

Template.listItemDetail.helpers({ 
    'idViaHelper':() => { 
     return this._id 
}) 

至於我的內流星雲數據上下文的理解,使用#each設定了listItemDetail模板的每個實例上下文是從listItem助手返回的文檔。

而且,我在使用模板中的{{_id}}時會發生這種情況,因爲它顯示文檔的ID。

但如果我試圖通過幫助{{idViaHelper}}使用this._id獲得相同的_id,我得到undefined。當我嘗試console.log(this)時,它表明this指的是Window對象。但我不知道爲什麼。發生了什麼以及爲什麼數據上下文無法在模板助手中找到?

這是我的第一篇文章,感謝您的幫助!

回答

1

你是對的流星datacontext流。 你在做什麼工作。

你只會忘記this代表一個lambda函數。

從MDN閱讀部分詞彙這個,它比更好地解釋什麼,我會說:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

對於您的情況下,更簡單的方法,直接從你這個得到的datacontext上的助手是路過通常的匿名功能。

試試看:

Template.listItemDetail.helpers({ 
    'idViaHelper': function(){ 
     return this._id 
}) 

就是這樣。

你在這一件事上倒黴了,這裏沒有與流星有關的問題。

其他相關問題,你會發現有用:meteor helper functions, lambdas and lexical this

+0

感謝朱利安。我認爲箭頭函數純粹是ES2015中的一個語法變化(舊的聲明函數的方式將被棄用),但我想如果兩者存在技術差異和用途,那麼他們可能都會堅持下去。 – TL77

0

朱利安勒雷是關於詞彙this在他的回答是正確的。使用lambda表達式時會丟失數據上下文。然而,流星爲您提供的方式,而不詞彙this訪問您的模板數據,即:

Template.list.helpers({ 
    'listItem':() => List.find().fetch(); 
}); 

Template.listItemDetail.helpers({ 
    'idViaHelper':() => Template.currentData()._id 
}); 

您可以同時使用Template.currentData()Template.instance().data

此外,請注意,如果您有隻包含單個return語句的lambda表達式,則可以使用上述快捷鍵語法。

// ECMAScript 5 
var myFunc = function (a, b, c) { 
    return b * a - c; 
}; 

變爲:

// ECMAScript 6 
const myFunc = (a, b, c) => b * a - c; 
相關問題