2015-05-05 38 views
1

我正在使用typeahead.js 0.11.1並嘗試對來自遠程源的結果進行排序。根據代碼,應該有可能覆蓋獵狗的默認排序功能。但我的排序功能從來沒有被調用過。識別功能相同。如何將搜索結果排序在先頭/血獵犬上?

這裏是我的代碼:

var bloodhoundSearchEngine = new Bloodhound({ 
    // we do not need any tokenization cause this will be done on the server 
    datumTokenizer : function(d) { 
     return d; 
    }, 
    queryTokenizer : function(q) { 
     return q; 
    }, 
    sorter : function(itemA, itemB) { 
     console.log(itemA); 
     if (itemA.count < itemB.count) { 
      return -1; 
     } else if (itemA.count > itemB.count) { 
      return 1; 
     } else 
      return 0; 
    }, 
    identify : function(item) { 
     console.log(itemA); 
     return item.value; 
    }, 
    remote : { 
     url : '/suggest/?term=%term', 
     wildcard : '%term', 
     transform : function(response) { 
      return $.map(response.suggestItems, function(item) { 
       return { 
        value : item.value, 
        count : item.count 
       }; 
      }); 
     }, 
     rateLimitBy : 'debounce', 
     rateLimitWait : 300 
    } 
}); 

$('#typeaheadinput .typeahead') 
     .typeahead(
       { 
        hint : true, 
        highlight : true, 
        minLength : 1 
       }, 
       { 
        name : 'existing-names', 
        display : 'value', 
        limit : 20, 
        source : bloodhoundSearchEngine.ttAdapter() 
       }); 

有沒有人在任何提示如何實現這一目標?

+0

請問您可以在http://jsfiddle.net上創建演示嗎? – Dhiraj

+0

從來沒有嘗試過jsfiddle.net,但我找到了解決問題的方法。看到我的答案。 –

回答

4

分揀機未被調用,因爲我使用自定義轉換函數來轉換來自遠程服務器的建議。因此,我在轉換函數中包含了對分類器的調用。以下代碼適用於我:

var bloodhoundSearchEngine = new Bloodhound({ 
    // we do not need any tokenization cause this will be done on the server 
    datumTokenizer : function(d) { 
     return d; 
    }, 
    queryTokenizer : function(q) { 
     return q; 
    }, 
    sorter : function(itemA, itemB) { 
     console.log(itemA); 
     if (itemA.count < itemB.count) { 
      return -1; 
     } else if (itemA.count > itemB.count) { 
      return 1; 
     } else 
      return 0; 
    }, 
    identify : function(item) { 
     console.log(itemA); 
     return item.value; 
    }, 
    remote : { 
     url : '/suggest/?term=%term', 
     wildcard : '%term', 
     transform : function(response) { 
      return $.map(bloodhoundSearchEngine.sorter(response.suggestItems), function(item) { 
       return { 
        value : item.value, 
        count : item.count 
       }; 
      }); 
     }, 
     rateLimitBy : 'debounce', 
     rateLimitWait : 300 
    } 
}); 

$('#typeaheadinput .typeahead') 
     .typeahead(
       { 
        hint : true, 
        highlight : true, 
        minLength : 1 
       }, 
       { 
        name : 'existing-names', 
        display : 'value', 
        limit : 20, 
        source : bloodhoundSearchEngine.ttAdapter() 
       });