bindAll
util
Binds methods of an object to the object itself, overwriting the existing method.
Installation
Import
import { bindAll } from '@tulx/utils';Source Code
Implementation
/**
* Binds methods of an object to the object itself, overwriting the existing method.
*
* @param object - The object to bind and assign the bound methods to.
* @param methodNames - The object keys of methods to bind.
* @returns Returns object.
*
* @example
* ```ts
* const view = {
* 'label': 'docs',
* 'onClick': function() {
* console.log('clicked ' + this.label);
* }
* };
* bindAll(view, ['onClick']);
* ```
*/
export function bindAll<T extends Record<string, unknown>>(
object: T,
methodNames: readonly (keyof T)[]
): T {
for (const methodName of methodNames) {
const method = object[methodName];
if (typeof method === 'function') {
object[methodName] = method.bind(object) as T[keyof T];
}
}
return object;
}
Example
import { bindAll } from '@tulx/utils';
const view = {
'label': 'docs',
'onClick': function() {
console.log('clicked ' + this.label);
}
};
bindAll(view, ['onClick']);Related Functions
attempt
Attempts to invoke func, returning either the result or the caught error object.
cond
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
conforms
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.
flow
Creates a function that returns the result of invoking the given functions with the this binding of the created function.