使用 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 中