Simple Signal
This is a super-simple signals class inspired by Robert Penner's AS3Signals.
Signals are like Events, Delegates, or Callbacks on other languages or platforms. You can create a signal that other parts of the code can "listen" to. When that signal is dispatched, all listeners are called with the passed parameters.
SimpleSignal is created with TypeScript, but aimed to be used as a standard JavaScript library.
Install
npm install simplesignal
Usage
First, import your signal:
var SimpleSignal = require('simplesignal');
import SimpleSignal from 'simplesignal';
Then, you can create a signal. For example, inside a class:
public onSomethingHappened = new SimpleSignal();
Then other parts of the code can subscribe (listen) to that signal:
myClassObject.onSomethingHappened.add((id) => {
console.log("Something happened with an id of " + id);
});
Signals can then be dispatched with parameters:
onSomethingHappened.dispatch("some-id");
This will call all subscribed functions with the given parameter.
Full reference (JS)
onSomethingHappened = new SimpleSignal();
onSomethingHappened.add(myFunc);
onSomethingHappened.add(function() { ... });
onSomethingHappened.add(() => { ... });
onSomethingHappened.remove(myFunc);
onSomethingHappened.removeAll();
console.log(onSomethingHappened.numItems);
onSomethingHappened.dispatch(...args)
Additional TypeScript reference
If your project already uses TypeScript, it has the advantage of using SimpleSignal's definition files for strict typing.
In this case, one can use a generic interface to enforce the correct dispatch/listener parameters:
onSomethingHappened = new SimpleSignal<(action:string) => void>();
function myFunc(action:string) {
console.log(action);
}
onSomethingHappened.add(myFunc);
onSomethingHappened.dispatch("some-action")
License
MIT.