Thursday, 8 August 2013

Issue with re-intializing tyepahead

Issue with re-intializing tyepahead

This is my requirement: I need a user input text box, when user enters
some text it has to show suggestions from local data as well as remote
data (results comes from server based on input text). when user re-enters
different text it has to search again in local and again a call to server
to get new data.
I tried using twitter typeahead. Initially I was able to show suggestions
from local as well as remote data but only once as typeahead doesn't make
another remote call as it already has prefetched data in its memory. Then
I tried destorying and re-initializing typeahead on each user input (only
if user input is different from previous one, this check is already
there). But I am getting below error:
"TypeError: this.$menu is null"
Can anybody tell me what can be cause of this issue? Below are my code
samples (these are from a test page I created to sort out the problem):
typeahead initialization property -
var props = {
template:'<div>{{name}}_{{id}}</div>',
local:[
{id:"val1", name:"india"},
{id:"val2", name:"indiana"},
{id:"val3", name:"abcindjgaja"}
],
limit:10000,
valueKey:'name',
cache:false,
remote:{
url:<MYURL>,
beforeSend:function (jqXHR, settings) {
settings.url += $("#myTI").val(); //myTI is id of
input text box
},
filter:function (data) {
var dataSet = [];
for (var i = 0; i < data.length; i++) {
if
((data[i].name.toLowerCase()).indexOf($("#myTI").val().toLowerCase())
!= -1) {
dataSet.push({
name:data[i].name,
id:data[i].id
});
}
}
return dataSet;
}
},
engine:{
compile:function (template) {
return {
render:function (ctx) {
var temp = Handlebars.compile(template);
return temp(ctx);
}
}
}
}
};
Logic for initializing/re-initializing -
$("#myTI").keyup((function () {
return function (e) {
if (window[window.text]) {
clearTimeout(window[window.text]);
}
window.text = $("#myTI").val();
window[window.text] = window.setTimeout(process, 250);
function process() {
var dataFound = false;
for (var key in window.dataMap) {
if (!window.dataMap.hasOwnProperty(key)) {
continue;
}
if (window.text.indexOf(key) != -1) {
dataFound = true;
window.dataSetName = window.dataMap[key];
updateTypeahead();
break;
}
}
if (!dataFound) {
window.dataSetName = "typeahead" +
parseInt(Math.random() * 1000, 10);
window.dataMap[window.text] = window.dataSetName;
updateTypeahead();
}
}
}
}()));
if (!window.tyepahead) {
updateTypeahead();
}
function updateTypeahead() {
if (window.tyepahead) {
window.tyepahead.typeahead('destroy');
}
props.name = window.dataSetName;
window.tyepahead = $("#myTI").typeahead(props);
}

No comments:

Post a Comment