2015-05-13 67 views
2

我已經實現了typeahead.js和bloodhound與遠程數據源,它大多按預期工作。但是,我將typeLhead上的minLength設置爲2,同時我可以在2個字符(和3)之後看到ajax請求觸發,而typeahead僅在4個字符或更多字符後提供建議。有沒有從我的配置丟失(我正在使用typeahead.bundle.min.js)。typeahead.js bloodhound minLength不工作

var local_authorities = new Bloodhound({ 
    datumTokenizer: function (datum) { 
     return Bloodhound.tokenizers.whitespace(datum.value); 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    identify : function(datum) { 
     //console.log(datum); 
     return datum.value; 
    }, 
    remote: { 
     url: "/addresses/autocomplete_local_authorities/%QUERY", 
     wildcard: '%QUERY', 
     filter: function (data) { 
      // Map the remote source JSON array to a JavaScript object array 
      return $.map(data.local_authorities, function (local_authority) { 
       return { 
        id: local_authority.id, 
        value: local_authority.name 
       }; 
      }); 
     } 
    } 
}); 

$('.typeahead.local-authority').typeahead({ 
    hint: true, 
    highlight: true, 
    minLength: 2,   
}, { 
    limit: 8, 
    source: local_authorities, 
    displayKey: 'value', 
}) 
.on('typeahead:selected', function (e, item) { 
    $('[name="local_authority_ids"').val(item.id); 
}); 

謝謝。

+0

可以請你創建http://jsfiddle.net演示? – Dhiraj

+0

謝謝。我已經建立了這個jsfiddle,但遇到了另一個問題:https://jsfiddle.net/zy3xtpzt/4/我無法獲得血腥提交郵寄請求(我本來必須解決的),所以它無法獲取數據從jsfiddle中的/ echo/json返回。 – TimSpEdge

回答

3

一些調試表明,這是由函數async(suggestions)(線1719至1727年)引起的:

function async(suggestions) { 
    suggestions = suggestions || []; 
    if (!canceled && rendered < that.limit) { 
      that.cancel = $.noop; 
      rendered += suggestions.length; 
      that._append(query, suggestions.slice(0, that.limit - rendered)); 
      that.async && that.trigger("asyncReceived", query); 
    } 
} 

該錯誤是通過設置renderedsuggestions.length調用append之前引起的,因此,當被警犬recieving 5個或更多查詢結果suggestions.slice(0, that.limit - rendered)始終爲空,因爲標準limit爲5.

只有當遠程端點返回小於limit的對象時纔會添加建議,發生在您的情況f或4個字母或更多。由於我不是Typeahead和Bloodhound的開發者,因此我不想要(也沒有時間)來解釋爲什麼它已經被實現,以及如何修復,但是,快速解決方法是增加limit

它必須在第二個配置對象中設置,例如, $("#someId").typeahead({ ... }, {..., limit: 10, ...});

編輯:使用預輸入/獵犬v 0.11.1

+0

感謝您抽出寶貴時間進行調試。您的解決方法解決了我的問題。 – TimSpEdge

+0

它仍然沒有被修復......希望到2020年,Twitter能夠一起努力。你我懷疑它:) – Jeffz

相關問題