Я использую твиттер typeahead для выполнения вызова покоя и добавляю результат в список typeahead. Моя проблема в том, что запрос поступает на другом языке.
Поэтому я делаю вызов rest в API Google Translate, а затем выполняю Ajax Call, используя Jquery для моего бэкэнда в другой функции, отличной от typeahead.
Моя проблема в том, что время отладки Twitter Typeahead работает, когда я не выполняю явно вызов rest. Но для языка, отличного от английского Для каждого нажатия клавиши происходит вызов Rest. Так как я использую функцию при подготовке typeahead.
вот мой код
genericEngine: function(words) {
var that = this;
return new Bloodhound({
remote: {
'cache': false,
url: HOST,
rateLimitWait: 800,
prepare: function(query, settings) {
var cancelAjaxRequest = false;
query = that.removeHtmlTags(query);
if(localStorage.appLanguage !== "En") {
var sendResponseFreeText = that.debounce(function() {
console.log('Sending Response to Google translate API after delay (1000ms)');
that.synchronousTranslation(query, function(translateResponse) {
console.log(`Translating Response after delay: ${translateResponse}`);
// Now perform the freeText and then rules Call;
if(translateResponse !== undefined && translateResponse !== "")
that.freeTextCall(translateResponse);
});
}, 1000);
sendResponseFreeText();
cancelAjaxRequest = true;
}
var freetextQuery = {
"text": query,
"patient": JSON.parse(localStorage.patientRecord).uuid
}
var headersVal = {
"Accept": "application/json;charset=UTF-8",
"Content-Type": "application/json"
};
settings.headers = headersVal;
settings.type = "POST";
settings.data = JSON.stringify(freetextQuery);
settings.processData = false
// Cancel ajax if language not english and performing request using a Function
if(cancelAjaxRequest === true) {
settings.beforeSend = function(e) {
console.log(`Cancelling the Rest Call`);
e.abort();
};
}
return settings;
},
filter: function(parsedResponse) {
that.processFreeTextResponse(parsedResponse);
var EngineResult = [];
return EngineResult;
}
},
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.fullSearch);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
},
Код для функции Debounce
debounce:function(func, wait, immediate) {
var timeout;
return function executedFunction() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
},
Инициализация typeahead
initTypeahead: function() {
var genricEngine = that.genericEngine();
var original = $.fn.val;
$('#Area-frame').contents().find('#mainDiv').typeahead({
hint: false,
highlight: true,
}, , {
source: genricEngine.ttAdapter(),
display: 'label',
templates: {
suggestion: function(data) {
console.log("I found data");
console.log(data);
if (localStorage.lastWordSearch.length !== 0) {
var conceptTypeImg = that.getConceptTypeImg(data.class_id);
if (data.type === "summary") {
return '<li style="border-bottom: 1px solid rgba(0, 0, 0, 0.2);"><img src=' + conceptTypeImg + ' width="15" height="15" border="0">' + " " + data.text +
'<br><button id="add">Add</button> <button id="close">Remove</button></li>';
} else {
return '<li style="border-bottom: 1px solid rgba(0, 0, 0, 0.2);color:red;"><img src=' + conceptTypeImg + ' width="15" height="15" border="0">' + " " + data.text +
'<br><button>Remove</button></li>';
}
}
}
}
}).bind('typeahead:cursorchange', '.tt-suggestion', function(ev, suggestion) {
});
},
Я не поделился ненужным кодом для краткости. Поскольку я печатаю, есть дорогой отдых, собирающийся. Есть ли способ, которым я могу ограничить повторный вызов при каждом нажатии клавиши и отправить его после того, как пользователь перестал печатать.
(предположим, в течение определенного времени, например, 800 мс).
Я использовал функцию времени отладки, но она не работала, как ожидалось.