Currently, I am in the process of converting some JavaScript code to TypeScript and I am facing a challenge with defining the signature of a jQuery EventHandler.
In the original JavaScript code, simplified to more generic terms, there is an Observer prototype that subscribes to custom events triggered by an element:
Observer.prototype._subscribe = function() {
this._row.bind('onItemChanged', this, this._onChangedHandler);
};
Observer.prototype._onChangedHandler= function(event, someString, someObject) {
var that = event.data;
if (someString === '42') {
that.coolMethod(someObject);
} else if (someString === '69') {
that.otherCoolMethod(someObject);
}
};
In another prototype named Subject, the trigger method notifies the observer with the event along with at least two data parameters:
Subject.prototype.foo = function() {
// Trigger the event so Observer will be notified and pass in the string and the object (or any data whatsoever)
this._element.trigger("onItemChanged", ["42", this._data]);
};
When attempting to translate this logic into TypeScript, I encountered issues with defining the correct parameter types for the event handler:
export class Observer {
private _subscribe (): void {
this._element.bind('onItemChanged', this, this._onChangedHandler);
}
private _onChangedHandler(event: JQueryEventObject, someString: string, someObject: FooBarClass) {
let that = event.data as Observer;
if (someString === '42') {
that.coolMethod(someObject);
} else if (someString === '69') {
that.otherCoolMethod(someObject);
}
}
}
The TypeScript code above does not compile and throws an error related to incompatible types. How should the parameter types of the event handler be defined correctly?
P.S. Alternative suggestions involving using jQuery's on() instead of bind() are also welcomed.
P.P.S. Please note that while solutions involving the use of fat arrow notation to handle 'this' context are known, the focus here is on achieving type safety in the event handler method signature.