简体   繁体   中英

Getting Bloodhound to work

I'm implementing a typing suggestion functionality on my website using Typeahead.js/Bloodhound but I can't get Bloodhound to work. Here is the code:

var indicator_commands = new Bloodhound({
    datumTokenizer: function(d) {
        return Bloodhound.tokenizers.whitespace(d.defaultInput);
    },        
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '/static/indicator.json',
});

console.log (indicator_commands.index.serialize());
indicator_commands.initialize();
console.log (indicator_commands.index.serialize());

Here is part of the indicator.json:

[
    {   "name": "sma",
        "fullname": "Smooth Moving Average",
        "parameter": "sma,period,applied_to_optional,#color_optional;",
        "defaultInput": "sma,14,close,#ababab;",
        "tokens" : ["sma,14,close,#ababab;"],
        "short_help": "",
        "long_help": "",
    },

    {   "name": "ema",
        "fullname": "Exponential Moving Average",
        "parameter": "ema,period,applied_to_optional,#color_optional;",
        "defaultInput": "ema,14,close,#ababab;",
        "tokens" : ["ema,14,close,#ababab;"],
        "short_help": "",
        "long_help": "",
    }
]

I was expecting some data in indicator_commands but it showed none. What do I need to change to get it working?

Your JSON is invalid.

You have a comma after the lest member of the object, ie. "long_help" : "", that is messing up bloodhoubd, you have to remove that.

You should also beware that indicator_commands.initialize(); will return a Promise according to bloodhound docs, so you have no guarantee that it actually has been initialized on your second call to serialize() . Although the code as is with the JSON fixed worked for me, you should probably use the Promise :

indicator_commands.initialize().then(function(b) {
     console.log('Success');
     console.log(indicator_commands.index.serialize());
},
function(e) { console.log('Error'); } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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