Typeahead v0.10.2 & Bloodhound - Working With Nested JSON Objects

前端 未结 2 2029
天命终不由人
天命终不由人 2021-02-18 18:01

UPDATE

Based on the correct answer from @BenSmith (https://stackoverflow.com/users/203371/BenSmith) I was able to find my problem and found out I was no

2条回答
  •  野的像风
    2021-02-18 18:33

    You need to write the filter function so that it creates an array of javascript objects to use as the datums. The following should work (I haven't tested this):

    filter: function (response) {
                return $.map(response.songs, function (song) {
                    return {
                        title: song.title,
                        artistName: song.artist_name
                    };
                });
            }
    

    (an example of the filter function can be found here)

    And change your datumtokenizer to:

    datumTokenizer: function (datum) {
            return Bloodhound.tokenizers.whitespace(datum.title);
        }
    

    also change your displaykey to:

    displayKey: 'title'
    

    As this is the key which Typeahead will be using for searching.

    As for displaying the song name and artist in the list of suggestons, I suggest you use templating (e.g. Handlebars) for displaying the results. See the "Custom Template" example in Typeahead's examples page. Your suggestion mark-up will then look similar to the following:

    suggestion: Handlebars.compile('

    {{title}} by {{artistName}}

    ')

提交回复
热议问题