'EasyAutocomplete events - $(this) is always undefined
I try to use EasyAutocomplete on several elements simultaneously
but $(this)
always undefined, why?
$("#city_selector_suggest, $city_two, #city_down").easyAutocomplete({
url: "/templates/rm/js/ecity2.json",
getValue: function(element) {
return element.cdek_cityname;
},
list: {
onChooseEvent: function() {
var selectedItemValue = $(this).getSelectedItemData().cdek_id;
console.log(selectedItemValue);
},
match: {
enabled: true,
method: function(element, phrase) {
if(element.indexOf(phrase) === 0) {
return true;
} else {
return false;
}
}
}
}
});
Solution 1:[1]
A quick test shows that in EasyAutocomplete event handlers, the this
is used unconventionally, i.e. "not like jQuery does it".
What I would expect from a jQuery plugin:
this
inside an event handler points to a DOM element- the event handler gets at least one
event
argument and possibly an additionaldata
argument.
What EasyAutocomplete does:
this
is some sort of configuration object of the widget- there are no arguments for the event handler
The configuration object does not seem to provide any way of getting the widget or even the DOM element the widget is based on.
The closest thing to a solution for that would to use .each()
and bind the widgets individually, storing a reference to the current element.
$("#city_selector_suggest, #city_two, #city_down").each(function () {
var $self = $(this);
$self.easyAutocomplete({
url: "/templates/rm/js/ecity2.json",
getValue: function(element) {
return element.cdek_cityname;
},
list: {
onChooseEvent: function() {
var selectedItemValue = $self.getSelectedItemData().cdek_id;
console.log(selectedItemValue);
},
match: {
enabled: true,
method: function(element, phrase) {
return element.indexOf(phrase) === 0;
}
}
}
});
});
Not quite as elegant as calling .easyAutocomplete()
only onceābut not completely horrible, either.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tomalak |