Javascript simple events system inspired on angular.js' one.
Install cast.js via node package manager (npm):
$ npm install cast.js --save-dev
Import the file into your project:
<script src="node_modules/cast.js/dest/cast.min.js"></script>
Use the method $on
to subscribe an event with a given name:
cast.$on('my-custom-event', function(data) {
console.log('Event fired!');
console.log('data:', data);
});
And use the method $broadcast
to fire events with a given name. You can also send data:
var data = {
info: 'Some awesome info here'
};
cast.$broadcast('my-custom-event', data);
Unsubscribing from events works just like the angular.js' way, the $on
method will return the respective unsubscribe function for that event.
var unsubscribe = cast.$on('my-custom-event', callbackFn);
unsubscribe(); //event is now unsubscribed. eezy peezy
And that's it!