Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2015
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. var Events = function Events() {
  2. // This makes sure there won't be any monkey business, in case we forget to
  3. // instantiate Events with the `new` operator.
  4. if( !(this instanceof Events) ) {
  5. return new Events();
  6. }
  7.  
  8. // This is where the callbacks are saved grouped by their respective eventNames.
  9. this.events = {};
  10. };
  11.  
  12. // Subscribes to `eventName`, which means `callback` is added to `events` and will
  13. // be called, whenever `eventName` is emitted. Of course `callback` must be a named
  14. // function in case you want to be able to remove it via `Events#off` later.
  15. Events.prototype.on = function on(eventName, callback) {
  16. var events = this.events;
  17.  
  18. events[eventName] = events[eventName] || [];
  19. events[eventName].push(callback);
  20. };
  21.  
  22. // Unsubscribes to `eventName`, which means, if it exists, `callback` will be
  23. // deleted from `events` and thus will no longer be fired when `eventName` is
  24. // emitted. Of course callback must be a named function and must already be
  25. // subscribed to `eventName` in order for this to work.
  26. Events.prototype.off = function off(eventName, callback) {
  27. var events = this.events, i, n;
  28.  
  29. if(events[eventName]) {
  30. for(i = 0, n = events[eventName].length; i < n; i++) {
  31. if(events[eventName][i] === callback) {
  32. events[eventName].splice(i, 1);
  33. break;
  34. }
  35. }
  36. }
  37. };
  38.  
  39. // Subscribes `callback` to be called whenever `eventName` is emitted
  40. // but unsubscribes it automatically as soon as it's been called.
  41. Events.prototype.once = function once(eventName, callback) {
  42. var self = this,
  43. events = this.events;
  44.  
  45. var selfDeleting = function selfDeleting(event) {
  46. callback(event);
  47. self.off(eventName, selfDeleting);
  48. };
  49.  
  50. this.on(eventName, selfDeleting);
  51. };
  52.  
  53. // Publishes `eventName` which will fire all `callbacks subscribed to
  54. // `eventName`, whereby `eventData` will be passed to the respective
  55. // `callback` function, just like with regular events.
  56. Events.prototype.emit = function emit(eventName, eventData) {
  57. var events = this.events, callback, i, n;
  58.  
  59. if(events[eventName]) {
  60. for(i = 0, n = events[eventName].length; i < n; i++) {
  61. callback = events[eventName][i];
  62. if(callback) {
  63. callback(eventData || {});
  64. }
  65. }
  66. }
  67. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement