I created a class called SearchBox to handle interaction with the search (delayed trigger, search by pressing the enter key, preventing the search when it is active, synchronizing the results when the search is completed and the text is changed, etc.).
All class methods are prototypes designed to be accessed through this. In the following code, suppose that it pis a prototype of a class.
p.registerListeners = function () {
$(this.element).on('keypress', this.searchKeyPressed);
};
p.unregisterListeners = function () {
$(this.element).off('keypress', this.searchKeyPressed);
};
This does not work, because when the keypress event calls the handler searchKeyPressed, it does not do this in context this. The only solution I can come up with is one that only supports modern browsers, which links the callback to this, which actually creates a new function. Since it creates a new function, I have to cache it in order to delete it later, since I need to pass the same link to offwhat I passed on.
Is there a better way to do this than this, or is this normal?
var boundKeyPressed;
p.registerListeners = function () {
boundKeyPressed = this.searchKeyPressed.bind(this);
$(this.element).on('keypress', boundKeyPressed);
};
p.unregisterListeners = function () {
$(this.element).off('keypress', boundKeyPressed);
};
, , , jQuery.on , , this , . , on('eventname',instance.func), this "currentTarget" ( "target" ), on('eventname','selector',instance.func), this , . func , instance.