使用 Regexes 过滤

用于过滤服务器上的订阅的简单模式,使用正则表达式,响应式会话变量和 deps autoruns。

// create our collection
WordList =  new Meteor.Collection("wordlist");

// and a default session variable to hold the value we're searching for
Session.setDefault('dictionary_search', '');

Meteor.isClient(function(){
    // we create a reactive context that will rerun items when a Session variable gets updated 
    Deps.autorun(function(){
        // and create a subscription that will get re-subscribe to when Session variable gets updated
        Meteor.subscribe('wordlist', Session.get('dictionary_search'));
    });

    Template.dictionaryIndexTemplate.events({
        'keyup #dictionarySearchInput': function(evt,tmpl){
            // we set the Session variable with the value of our input when it changes
            Session.set('dictionary_search', $('#dictionarySearchInput').val());
        },
        'click #dictionarySearchInput':function(){
            // and clear the session variable when we enter the input
            Session.set('dictionary_search', '');
        },
    });
});
Meteor.isServer(function(){
    Meteor.publish('wordlist', function (word_search) {
        // this query gets rerun whenever the client subscribes to this publication
        return WordList.find({
            // and here we do our regex search
            Word: { $regex: word_search, $options: 'i' }
        },{limit: 100});
    });
});

以及客户端上使用的 HTML:

<input id="dictionarySearchInput" type="text" placeholder="Filter..." value="hello"></input>

这种模式本身非常简单,但正则表达式可能不是。如果你不熟悉正则表达式,这里有一些有用的教程和链接:

正则表达式教程
正则表达式备忘单
正则表达式在 Javascript 中