I'm trying to DRY out some JQuery code that initializes a typeahead.js plugin that uses the Bloodhound suggestion engine with a remote data source. This is the code so far:
var locsData = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/locations/search.json?q=%QUERY",
ajax: {
beforeSend: function(xhr, settings) {
$("#typeahead1").addClass('loading-text');
},
complete: function(xhr, status) {
$("#typeahead1").removeClass('loading-text');
}
}
},
limit: 100
});
locsData.initialize();
$("#typeahead1").typeahead({
minLength: 3
}, {
name: "locs",
displayKey: "name",
source: locsData.ttAdapter()
});
I'm trying to generalize this code for a bunch of different text fields; that should not be a problem: I could use $(".myClass").typeahead({ ... })
and the plugin would be initialized for all of those controls. The problem I'm facing is with the ajax
callback functions in the Bloodhound configuration (beforeSend
, complete
, etc.): I'm toggling a "loading.gif" class for the text field inside those functions, and I need that code to get a reference to the calling object.
How can I get a reference to the calling text field inside those callbacks? I need something like this:
$(<text-field reference>).addClass('loading-text');
I hope somebody could help me. Thanks in advance!
EDIT - For now I'm using the following code that somehow solves my problem, but the question about getting a calling object reference (the subject of this) is still pending.
if ($(document.activeElement).typeahead != null) {
$(document.activeElement).addClass('loading-text');
}