Skip to content

Instantly share code, notes, and snippets.

@Quickz
Last active July 18, 2020 22:38
Show Gist options
  • Save Quickz/f98c98ed0ede9966870fa48d6fb63e97 to your computer and use it in GitHub Desktop.
Save Quickz/f98c98ed0ede9966870fa48d6fb63e97 to your computer and use it in GitHub Desktop.
C# like event pattern for TypeScript
export type EventHandler<T> = (event: T) => void;
export interface IEvent<T>
{
add(handler: EventHandler<T>): void;
remove(handler: EventHandler<T>): void;
}
export class InvokeableEvent<T> implements IEvent<T>
{
private handlers: EventHandler<T>[] = [];
/**
* @param handler Method that will be called when event is invoked.
*/
public add(handler: EventHandler<T>)
{
this.handlers.push(handler);
}
/**
* @param handler An existing method that is called when event is invoked.
*/
public remove(handler: EventHandler<T>)
{
for (let i = 0; i < this.handlers.length; i++)
{
if (this.handlers[i] === handler)
{
this.handlers.splice(i, 1);
}
}
}
/**
* Runs all the methods that were added.
* @param event An argument that handlers expect (Use null if none are expected).
*/
public invoke(event: T)
{
for (let handler of this.handlers)
{
handler(event);
}
}
}
import { InvokeableEvent, IEvent } from "./EventSystem";
export class Example
{
public static run()
{
let button: Button = new Button();
button.onClicked.add(this.onButtonClicked);
button.click();
button.click();
button.onClicked.remove(this.onButtonClicked);
button.click();
}
private static onButtonClicked = () =>
{
console.log('Button has been clicked!');
}
}
class Button
{
public get onClicked(): IEvent<null> { return this._onClicked; }
private _onClicked: InvokeableEvent<null> = new InvokeableEvent();
public click()
{
this._onClicked.invoke(null);
}
}
// Code snippet for making an event instance in VS Code
{
"Create an event": {
"prefix": "ent",
"body":
[
"public get $1(): IEvent<$2> { return this._$1; }",
"private _$1: InvokeableEvent<$2> = new InvokeableEvent<$2>();"
],
"description": "Create an event instance. Pattern source: https://gist.github.com/Quickz/f98c98ed0ede9966870fa48d6fb63e97"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment