Skip to content

[Typescript SimpleEvents] Simple Cancelable Data Event

Face of Cat edited this page Apr 30, 2017 · 1 revision

An event type that provides data to its callbacks and returns a (boolean | undefined) value allowing callback functions to cancel an action.

Class Information

export interface CancelableDataEvent<D> {
    on(callback: (data: D) => boolean): number;
    off(handle: number): void;
    trigger(data: D): boolean | undefined;
}

export class SimpleCancelableDataEvent<D> extends BaseEvent<D, boolean> implements CancelableDataEvent<D> {
    on= (callback: (data: D) => boolean): number => super.add(callback);
    off= (handle: number): void => super.remove(handle);
    trigger= (data: D): boolean | undefined => super.getResult(data, 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;

Example Usage

the following test.ts compiled into test.js:

import { SimpleCancelableDataEvent as CancelableDataEvent } from "typescript-simpleevents";

class EventTest {
    readonly cancelAction = new CancelableDataEvent<number>();

    doAction(index: number) {
       if (!this.cancelAction.trigger(index)) {
           console.log(`Action ${index}!`);
       }
    }
}

const test = new EventTest();
const handle = test.cancelAction.on(x => x == 2);
test.doAction(1);
test.doAction(2);
test.doAction(3);

wil have the output:

> node test.js
Action 1!
Action 3!

Clone this wiki locally