Skip to content

Instantly share code, notes, and snippets.

@obrassard
Last active November 3, 2020 22:18
Show Gist options
  • Save obrassard/5082c857f248e848f2db357dcc881a0a to your computer and use it in GitHub Desktop.
Save obrassard/5082c857f248e848f2db357dcc881a0a to your computer and use it in GitHub Desktop.
This class, inspired by C# delegation system, allow dynamic mapping of several functions/methods inside a single "delegate" object which can later be invoked or passed as a function

ActionDelegate

This class, inspired by C# multicast delegation system, allow dynamic mapping of several functions/methods inside a single "delegate" object which can later be invoked or passed as a function.

How to use ?

import { ActionDelegate } from './ActionDelegate';

let delegate = new ActionDelegate();

let f1 = (a:string) => {
    console.log(`hello ${a} from 1`);
}

function f2(a:string) {
    console.log(`hello ${a} from 2`);
}

let f3 = function (a:string) {
    console.log(`hello ${a} from 3`);
}

let action = delegate.add(f1).add(f3).add(f2).asFunction();
action('Bob');

Prints :

hello Bob from 1
hello Bob from 3
hello Bob from 2

Methods details

add(f:DelegateFunction): ActionDelegate

Adds (register) a given function or method to this delegate

remove(f:DelegateFunction): ActionDelegate

Remove (unregister) a given function or method of this delegate

invoke(...args: any[]): DelegateFunction

Invoke this delegate with the given arguments

Call all registered functions with the given args

asFunction(): DelegateFunction

Returns a function that can be called to invoke the delegate

Example :

let action = new ActionDelegate().add(f1).add(f3).add(f2).asFunction();
action(`Bob`);

// Has the same result than
new ActionDelegate().add(f1).add(f3).add(f2).run('Bob');
type DelegateFunction = (...args: any[]) => void;
export class ActionDelegate {
private delegation: DelegateFunction[];
constructor() {
this.delegation = []
}
public add(f: DelegateFunction): ActionDelegate {
this.delegation.push(f);
return this;
}
public remove(f: DelegateFunction): ActionDelegate {
let i = this.delegation.indexOf(f)
if (i !== -1) {
this.delegation.splice(i, 1);
}
return this;
}
public asFunction(): DelegateFunction {
return this.invoke.bind(this);
}
public invoke(...args: any[]): DelegateFunction {
this.delegation.forEach(f => f(...args))
return this.asFunction();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment