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 w开发者_Go百科ant 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]:
Activities.splice(0, Activities.length, _json[0], _json[1], ...);
This would remove all elements (from 0
to Activities.length
) and add each element from the _json
array.
But _json
might contain an unknown number of elements, and hardcoding it like we did above is very bad. Fortunately, we can use the apply
[MDN] method to call a method with a variable number of arguments, provided as array:
var params = [0, Activities.length].concat(_json);
Activities.splice.apply(Activities, params);
This is the equivalent to the call above, but adding all elements from _json
.
Reference: concat
, splice
, apply
精彩评论