简体   繁体   English

流星:从事件更改db.find()

[英]Meteor: change db.find() from an event

I have a template with an <#each>. 我有一个带有<#each>的模板。

    <template name="listing">

        {{#each adList}}

            {{> adItemTemplate}}

        {{/each}}

    </template>

I'm sending data to the <#each> using this code: 我正在使用以下代码将数据发送到<#each>:

    Template.listing.adList = function(){

        return listingDB.find()

    }

This gives me a nice list of the articles. 这给了我很好的文章清单。 However, i have a button that narrows the listing with this. 但是,我有一个按钮可以缩小列表的范围。

listingDB.find({location:"newyork"})

I'm trying to do it with an event but nothing happens: 我正在尝试通过一个事件来做,但是什么也没有发生:

    Template.narrowSearch.events({

        "click .search":function(){

            listingDB.find({location:"newyork"})

        }

    })

What am i missing? 我想念什么?

thx, 谢谢,

Two things to bear in mind: 需要牢记两件事:

  1. Your template will only ever render what the helper function returns, and there's nothing in your code that's going to change what that is. 您的模板将仅呈现辅助函数返回的内容,并且您的代码中没有任何内容可以更改其内容。 You're running a completely separate database query in the event handler, the results of which won't go anywhere. 您正在事件处理程序中运行一个完全独立的数据库查询,其结果将不会随处可见。

  2. In order to have you template helper rerun reactively when you change some setting, it needs to depend on a reactive data source . 为了使您的模板助手在更改某些设置时能够被动地重新运行,它需要依赖于被动数据源

So the upshot of all that is that you should be doing something like: 因此,所有这些操作的结果就是您应该执行以下操作:

Session.set("query", {});

Template.listing.adList = function() {
    return listingDB.find(query);
}

Template.narrowSearch.events({
    "click .search":function() {
        Session.set(query, {
            location: "newyork"
        });
    }
})

Note that a session variable is not the only (or necessarily the correct) way to provide this reactivity - if you want something more private, use a ReactiveVar . 请注意,会话变量不是提供这种反应性的唯一(或必然是正确的)方法-如果您想要更私有的内容,请使用ReactiveVar

Template.listing.adList = function(){
    var query = Session.get('query') || {};

    return listingDB.find(query);

}

Template.narrowSearch.events({

    "click .search":function(){
        Session.set(query, {location: 'newyork'});

    }

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM