EventDispatcher.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var EventDispatcher = function () {};
  5. Object.assign( EventDispatcher.prototype, {
  6. addEventListener: function ( type, listener ) {
  7. if ( this._listeners === undefined ) this._listeners = {};
  8. var listeners = this._listeners;
  9. if ( listeners[ type ] === undefined ) {
  10. listeners[ type ] = [];
  11. }
  12. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  13. listeners[ type ].push( listener );
  14. }
  15. },
  16. hasEventListener: function ( type, listener ) {
  17. if ( this._listeners === undefined ) return false;
  18. var listeners = this._listeners;
  19. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  20. return true;
  21. }
  22. return false;
  23. },
  24. removeEventListener: function ( type, listener ) {
  25. if ( this._listeners === undefined ) return;
  26. var listeners = this._listeners;
  27. var listenerArray = listeners[ type ];
  28. if ( listenerArray !== undefined ) {
  29. var index = listenerArray.indexOf( listener );
  30. if ( index !== - 1 ) {
  31. listenerArray.splice( index, 1 );
  32. }
  33. }
  34. },
  35. dispatchEvent: function ( event ) {
  36. if ( this._listeners === undefined ) return;
  37. var listeners = this._listeners;
  38. var listenerArray = listeners[ event.type ];
  39. if ( listenerArray !== undefined ) {
  40. event.target = this;
  41. var array = [], i = 0;
  42. var length = listenerArray.length;
  43. for ( i = 0; i < length; i ++ ) {
  44. array[ i ] = listenerArray[ i ];
  45. }
  46. for ( i = 0; i < length; i ++ ) {
  47. array[ i ].call( this, event );
  48. }
  49. }
  50. }
  51. } );