meteor,动态更改模板帮助程序数据

时间:2014-03-04 20:37:50

标签: meteor

我有一个小疑问,是否可以动态更改模板助手数据。

这是我的模板

{{#each post}}
<h4>{{postyname}}</h4>
<h4>{{Headline}}</h4>
<h4>{{Location}}</h4>
{{/each}}

这是我的帮助数据

post:function()
{
    posts.find({},{sort: {createdAt: -1}}).fetch();
}

它在我的主页上显示结果,我在此页面顶部有搜索栏,每当用户点击搜索按钮时,必须渲染相同的模板,但不同的数据取决于用户搜索。

我在onclick事件中尝试过这样的事情,看起来它不起作用

'onclick #searchBtn':function()
{
    var all_posts=posts.find({'Headline': search},{sort: {createdAt: -1}}).fetch();

    Template.postDisplay.post=function(){

    return all_posts;
}

怎么做?

2 个答案:

答案 0 :(得分:7)

我相信使用Dep Dependency是你想要使用的:

在js文件的顶部创建一个变量

var _deps = new Tracker.Dependency;
var searchCriteria = {};

在你的帮手中:

post:function() {
    _deps.depend(); // creates a dependency between the accessor of "post" and the _deps
    posts.find(searchCriteria,{sort: {createdAt: -1}}).fetch();
}

点击按钮:

'onclick #searchBtn':function() {
    searchCriteria = {'Headline': search};
    _deps.changed(); // notifying everyone that is dependent on _deps that it has changes
}

根据我从你的问题中看到的情况,我相信这应该可以处理你的情况。如果我误解了你的问题,请告诉我。

答案 1 :(得分:5)

为什么不使用Session变量?它们是被动的,正是你所需要的。

使用Session.set和Session.get代替手动处理依赖项,而不是自动注册和解除依赖项。

post:function()
{
    var searchCriteria = Session.get("searchCriteria") || {};
    posts.find(searchCriteria,{sort: {createdAt: -1}}).fetch();
}

'onclick #searchBtn':function()
{
    Session.set("searchCriteria", {'Headline': search});
}

在热代码重新加载后,Session变量也会被保留。变量不会。