目前,我的 Meteor.js 网站上有一个部分,用于在空格键模板中呈现响应式(Reactive)集合中的标签。
我做了这样简单的事情:
//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>
这按其应有的方式 react 性地工作。
我的问题是:
How can I change what the helper is returning and force an update to the template?
我希望根据搜索栏过滤标签的结果。
因此,当用户开始在 tagsSearchBar 中输入内容时,我需要更改 tagsTemplate 中显示的内容。
我可以进行文本搜索并返回结果,但我不确定如何更新帮助程序,然后强制重新加载模板。
如果我尝试简单地更改模板辅助函数的定义,则模板不会更新为新定义(我认为模板不知道辅助函数的定义更改)。
基本上,我试图弄清楚如何为自己的目的进行空格键 react 。
谢谢大家!
最佳答案
如果您确实想更改辅助函数并在执行此操作时重新渲染模板,一种方法是将函数存储在 react 变量中,然后在辅助程序中从 react 变量获取函数并执行它。不幸的是,您无法在 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)
但是,可能有更合适的解决方案。如果您在搜索栏中输入内容时的界面行为与搜索栏为空时的界面行为完全不同,您可能需要一个单独的模板,然后决定以 react 方式显示哪个模板。如果行为基本相同,则将此逻辑添加到现有帮助程序中可能会更简单,例如:
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
关于javascript - 渲染模板后,如何更改空格键中的模板辅助函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23863710/