I’m fairly new to javascript. I downloaded some code to make an autocompleter for search boxes, but it’s not working as I expected it.
This is the code that I downloaded:
Autocompleter.Local = new Class({
Extends: Autocompleter,
initialize: function (element, tokens, options) {
this.parent(element, options);
console.log(tokens); // I added this
this.tokens = tokens;
},
query: function () {
console.log(this.tokens); // and this
this.update(this.filter());
}
});
To make use of this code, I do this:
var Activities = ['aa', 'bb', 'cc', 'abcd'];
function InitializePage() {
new Autocompleter.Local('txtSearch', Activities, {
'minLength': 1, // We wait for at least one character
'overflow': false, // Overflow for more entries
'selectMode': 'type-ahead'
});
}
window.addEvent('domready', function () {
InitializePage();
});
The tokens parameter for the initialize function is an array of all the possible things that the autocompleter might suggest. the filter() function filters these so only relevant ones are displayed to the user. What I want to do is change the tokens array at various times so different things are suggested to the user.
I tried doing this:
new Request.JSON({ method: 'get', url: 'handler/GetActivities.ashx', autoCancel: true, urlEncoded: false, secure: false,
headers: { "Content-type": "application/json" },
onSuccess: function (_json, _jsonText) {
Activities = _json;
}
}).send();
I have confirmed that the Activities variable is being updated by this request. However, the tokens variable inside the autocompleter class remains as the array that it was initialized as.
How do I get it so that the tokens variable points to the same data as the activities variable?
The problem is that you are overriding the array. You should replace the elements instead. You can add and remove elements in-place with
splice[MDN]:This would remove all elements (from
0toActivities.length) and add each element from the_jsonarray.But
_jsonmight contain an unknown number of elements, and hardcoding it like we did above is very bad. Fortunately, we can use theapply[MDN] method to call a method with a variable number of arguments, provided as array:This is the equivalent to the call above, but adding all elements from
_json.Reference:
concat,splice,apply