Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

javascript - Twitter Typeahead.js how to return all matched elements within a string

By default twitter typeahead.js returns only elements matched in the begining of a string, for example:

source: ['type','typeahead','ahead']

query: 'type'

returns: 'type' and 'typeahead'

--

query: 'ahead'

returns: 'ahead'

I want it to return 'ahead' and 'typeahead'

my code:

var clients = new Bloodhound({
    datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    prefetch: {
        url: '/clients.json',
        filter: function(list) {
            return $.map(list, function(value) { return { name: value }; });
        }
    }
});

clients.initialize();

$('.client').typeahead(null, {
    displayKey: 'value',
    source: clients.ttAdapter(),
    minLength: 1,
});

There is already a question about it but i didnt understand the answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found a solution... the problem was that I was so used to bootstrap2 typeahead that I wasn't understanding the datumTokenizer thing. If someone else find it hard to understand, I will put a little description below:

queryTokenizer: array of words you are querying, if you query for 'test abcd' it will transform the string into ['test','abcd'] and than look for matches with those two words.

datumTokenizer : array of words it will be matched with queryTokenizer. Each item from your JSON will have a set of words to be matched.

So if you have a source:

['good test','bad test']

and query for 'est'. You need to make datumTokenizer return an array containing 'est' , something like:

['good','test','ood','od','test', 'est', 'st'] for the first item

['bad','ad','test', 'est', 'st'] for the second item

Bellow is the code I wrote, I don't know if its the optimal thing for it, but I think it will help anyway:

new Bloodhound({
    datumTokenizer: function(d) {
        var test = Bloodhound.tokenizers.whitespace(d.value);
            $.each(test,function(k,v){
                i = 0;
                while( (i+1) < v.length ){
                    test.push(v.substr(i,v.length));
                    i++;
                }
            })
            return test;
        },
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    limit: 10,
    prefetch: {
        url: '/lista.json',
        ttl: 10000
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...