Repository navigation
[Typescript SimpleEvents] Simple Cancelable Event
Face of Cat edited this page Apr 30, 2017
·
2 revisions
An event type that returns a (boolean | undefined) value allowing callback functions to cancel an action.
export interface CancelableEvent {
on(callback: ()=> boolean): number;
off(handle: number): void;
trigger(): boolean | undefined;
}
export class SimpleCancelableEvent extends BaseEvent<void, boolean> implements CancelableEvent {
on= (callback: () => boolean): number => super.add(callback);
off= (handle: number): void => super.remove(handle);
trigger= (): boolean | undefined => super.getResult(undefined, false);
}- on: adds a callback to the invoke list and returns its handle;
- off: removes a callback from the invoke list based on its handle;
- trigger: invokes all the callback in order; if there are no callback registered it will return undefined; if there is at least one callback it will return true if at least one callback returns true, or false otherwise;
the following test.ts compiled into test.js:
import { SimpleCancelableEvent } from "typescript-simpleevents";
class EventTest {
readonly cancelAction = new SimpleCancelableEvent();
doAction(index: number) {
if (!this.cancelAction.trigger()) {
console.log(`Action ${index}!`);
}
}
}
const test = new EventTest();
test.doAction(1);
const handle = test.cancelAction.on(() => true);
test.doAction(2);
test.cancelAction.off(handle);
test.doAction(3);wil have the output:
> node test.js
Action 1!
Action 3!