es6.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. 'use strict';
  2. class EventPubSub {
  3. constructor( scope ) {
  4. this._events_ = {};
  5. this.publish = this.trigger = this.emit;
  6. this.subscribe = this.on;
  7. this.unSubscribe = this.off;
  8. }
  9. on( type, handler, once ) {
  10. if ( !handler ) {
  11. throw new ReferenceError( 'handler not defined.' );
  12. }
  13. if ( !this._events_[ type ] ) {
  14. this._events_[ type ] = [];
  15. }
  16. if(once){
  17. handler._once_ = once;
  18. }
  19. this._events_[ type ].push( handler );
  20. return this;
  21. }
  22. once( type, handler ) {
  23. return this.on( type, handler, true );
  24. }
  25. off( type, handler ) {
  26. if ( !this._events_[ type ] ) {
  27. return this;
  28. }
  29. if ( !handler ) {
  30. throw new ReferenceError( 'handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler' );
  31. }
  32. if ( handler == '*' ) {
  33. delete this._events_[ type ];
  34. return this;
  35. }
  36. const handlers = this._events_[ type ];
  37. while ( handlers.includes( handler ) ) {
  38. handlers.splice(
  39. handlers.indexOf( handler ),
  40. 1
  41. );
  42. }
  43. if ( handlers.length < 1 ) {
  44. delete this._events_[ type ];
  45. }
  46. return this;
  47. }
  48. emit( type, ...args ) {
  49. if ( !this._events_[ type ] ) {
  50. return this.emit$( type, ...args );
  51. }
  52. const handlers = this._events_[ type ];
  53. const onceHandled=[];
  54. for ( let handler of handlers ) {
  55. handler.apply( this, args );
  56. if(handler._once_){
  57. onceHandled.push(handler);
  58. }
  59. }
  60. for(let handler of onceHandled){
  61. this.off(type,handler);
  62. }
  63. return this.emit$( type, ...args );
  64. }
  65. emit$( type, ...args ) {
  66. if ( !this._events_[ '*' ] ) {
  67. return this;
  68. }
  69. const catchAll = this._events_[ '*' ];
  70. for ( let handler of catchAll ) {
  71. handler.call( this, type, ...args );
  72. }
  73. return this;
  74. }
  75. }
  76. module.exports = EventPubSub;