Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Events = function Events() {
- // This makes sure there won't be any monkey business, in case we forget to
- // instantiate Events with the `new` operator.
- if( !(this instanceof Events) ) {
- return new Events();
- }
- // This is where the callbacks are saved grouped by their respective eventNames.
- this.events = {};
- };
- // Subscribes to `eventName`, which means `callback` is added to `events` and will
- // be called, whenever `eventName` is emitted. Of course `callback` must be a named
- // function in case you want to be able to remove it via `Events#off` later.
- Events.prototype.on = function on(eventName, callback) {
- var events = this.events;
- events[eventName] = events[eventName] || [];
- events[eventName].push(callback);
- };
- // Unsubscribes to `eventName`, which means, if it exists, `callback` will be
- // deleted from `events` and thus will no longer be fired when `eventName` is
- // emitted. Of course callback must be a named function and must already be
- // subscribed to `eventName` in order for this to work.
- Events.prototype.off = function off(eventName, callback) {
- var events = this.events, i, n;
- if(events[eventName]) {
- for(i = 0, n = events[eventName].length; i < n; i++) {
- if(events[eventName][i] === callback) {
- events[eventName].splice(i, 1);
- break;
- }
- }
- }
- };
- // Subscribes `callback` to be called whenever `eventName` is emitted
- // but unsubscribes it automatically as soon as it's been called.
- Events.prototype.once = function once(eventName, callback) {
- var self = this,
- events = this.events;
- var selfDeleting = function selfDeleting(event) {
- callback(event);
- self.off(eventName, selfDeleting);
- };
- this.on(eventName, selfDeleting);
- };
- // Publishes `eventName` which will fire all `callbacks subscribed to
- // `eventName`, whereby `eventData` will be passed to the respective
- // `callback` function, just like with regular events.
- Events.prototype.emit = function emit(eventName, eventData) {
- var events = this.events, callback, i, n;
- if(events[eventName]) {
- for(i = 0, n = events[eventName].length; i < n; i++) {
- callback = events[eventName][i];
- if(callback) {
- callback(eventData || {});
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement