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.
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
Adds (register) a given function or method to this delegate
Remove (unregister) a given function or method of this delegate
Invoke this delegate with the given arguments
Call all registered functions with the given args
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');