Wednesday, December 2, 2009

[jQuery] [autocomplete] FIX: Cache using term + extraParams

Hi all,

i have made a change to autocomplete code, because cache handling
should include extraParams in cache term. I thought this could be
interesting for some of you, so here is the code snippet that should
replace existing function "request" in autocomplete.js :


function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
//FIX: extraParams should be included in cacheTerm
var cacheTerm = term;
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
var extP = typeof param == "function" ? param() : param;
extraParams[key] = extP;
cacheTerm = cacheTerm + "_" + key + ":" +extP;
});


var data = cache.load(cacheTerm);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length >
0) ){

$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(cacheTerm, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents
the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};

No comments: