Skip to content

Instantly share code, notes, and snippets.

@DanTup
Created May 30, 2014 17:48
Show Gist options
  • Save DanTup/0def28423f81c6d35d33 to your computer and use it in GitHub Desktop.
Save DanTup/0def28423f81c6d35d33 to your computer and use it in GitHub Desktop.
// A list of all event types; these are basically used as strings, because we can't(?)
// get a nice unique name from a TS Class to use for the event name
enum EventType {
SendTheStuff
};
// All events must at least give us the EventType that we can convert to a string
interface IEvent {
EventType: EventType;
};
// A sample event; which just passes a number
class SendTheStuffEvent implements IEvent {
EventType = EventType.SendTheStuff;
constructor(public SendHowMany: number) { }
};
// Dispatches an event (details ommited to avoid needing CustomError stuff)
function Dispatch(event : IEvent) {
window.dispatchEvent(null); //
}
// Adds an event listener for a given type of event.
// The first arg is the "class" and must extend IEvent and have an EventType type
// that we can convert to a string as the event name.
// The second arg is the callback function, which we want to force to take a
// single arg, which is the event that was raised
function Listen<T extends IEvent>(eventType: { new (number): T; prototype: { EventType: EventType } }, callback: (T) => void) {
// This only currently works because we have "new (number)"... We're forcing a specific type
// of constructor; but we don't care what this is, we just need TypeScript to be able to
// infer the T.
window.addEventListener(eventType.prototype.EventType.toString(), callback);
}
// Use it like this:
// Subscribe to the event with Listen
var logStuffSending = function (e : SendTheStuffEvent) { console.log('Please send ' + e.SendHowMany); };
Listen(SendTheStuffEvent, logStuffSending);
// Send an event with Dispatch
Dispatch(new SendTheStuffEvent(50));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment