[英]How do I change template helper function in Spacebars after template has been rendered?
目前,我在Meteor.js網站上有一個部分,該部分在Spacebars Template中呈現來自反應式集合的標簽。
我這樣做很簡單:
//Coffeescript Template Helper
Template.Albums.tags = ->
tags = []
_.each Albums.find({}).fetch(), (albumObject, index) ->
tags = _.union(albumObject.tags, tags)
return tags;
<!-- Spacebars Template -->
<template name="tagsTemplate">
{{#each tags}}
<li class="interfaceItem">
<a class="tag" href="{{this}}/">
{{this}}
</a>
</li>
{{/each}}
</template>
這可以按需進行反應。
我的問題是:
如何更改幫助程序返回的內容並強制更新模板?
我希望根據搜索欄過濾標簽的結果。
因此,當用戶開始鍵入tagsSearchBar時 ,我需要更改tagsTemplate中顯示的內容 。
我可以進行文本搜索並返回結果,但是我不確定如何去更新助手,然后強制重新加載模板。
如果我嘗試簡單地更改模板助手功能的定義,則模板不會更新為新定義(我認為模板不知道助手功能的定義更改)。
基本上,我試圖弄清楚如何為自己的目的進行空格鍵反應。
感謝大家!
如果您確實要更改輔助函數並在執行時重新渲染模板,則一種方法是將函數存儲在反應變量中,然后在您的助手中,從反應變量中獲取函數並執行它。 不幸的是,您不能在Session中存儲函數,因此您必須使用Deps.Dependency
:
defaultTagFunction = ->
tags = []
_.each Albums.find({}).fetch(), (albumObject, index) ->
tags = _.union(albumObject.tags, tags)
return tags
searchTagFunction = ->
# do something else
tagFunction = ->
tagFunctionDependency = new Deps.Dependency()
Template.Albums.tags = ->
tagFunctionDependency.depend()
return tagFunction() # tagFunction.call(this) if you need the data context
setTagFunction = (fn) ->
tagFunction = fn
tagFunctionDependency.changed()
setTagFunction(defaultTagFunction)
# later
setTagFunction(searchTagFunction)
但是,可能有一個更合適的解決方案。 如果在您輸入搜索欄時界面的行為與在搜索欄為空時的界面行為完全不同,則您可能需要一個單獨的模板,然后確定要被動顯示的模板。 如果行為基本相同,則將這種邏輯添加到現有助手中可能會更簡單,例如:
Template.Albums.tags = ->
searchText = Session.get("tagsSearchBar")
if searchText is ""
cursor = Albums.find({})
else
cursor = Albums.find({tags: searchText})
tags = []
_.each cursor.fetch(), (albumObject, index) ->
tags = _.union(albumObject.tags, tags)
return tags
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.