In the given code snippet, the first instance of "this" is determined by the data table typings:
every(fn: (this: ColumnMethods, colIdx: number, tableLoop: number, colLoop: number) => void): Api;
The second reference to "this" implicitly refers to an HTMLElement, and this inference is based on the definitions of on
and JQuery.EventHandler
.
interface JQuery<TElement = HTMLElement> extends Iterable<TElement> {
on(events: string,
handler: JQuery.EventHandler<TElement> | JQuery.EventHandlerBase<any, JQuery.Event<TElement>> | false): this;
}
interface EventHandler<TCurrentTarget, TData = null> extends EventHandlerBase<TCurrentTarget, Event<TCurrentTarget, TData>> { }
interface EventHandlerBase<TContext, T> {
// The source of the type for this, some generics involved
(this: TContext, t: T, ...args: any[]): void | false | any;
}
In order to access the value
property, it is recommended to explicitly specify the type of HTMLElement
when invoking $
, ensuring that "this" inside the handler passed to on
is correctly typed.
var table = $('#example').DataTable();
table.columns().every(function () {
var that: DataTables.ColumnMethods = this; // redundant but we can specify it
// We can specify the result we expect to the $ function
$<HTMLInputElement>('input').on('keyup change', function () { // required to access value
that
.search(this.value)
.draw();
});
})