event.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * The function for providing an Event object simply managing events.
  3. *
  4. * @author Naotoshi Fujita
  5. * @copyright Naotoshi Fujita. All rights reserved.
  6. */
  7. import { each } from "../utils/object";
  8. /**
  9. * The function for providing an Event object simply managing events.
  10. */
  11. export default () => {
  12. /**
  13. * Store all handlers.
  14. *
  15. * @type {Object}
  16. */
  17. const handlers = {};
  18. return {
  19. /**
  20. * Subscribe the given event(s).
  21. *
  22. * @param {string} event - An event name. Use space to separate multiple events.
  23. * Also, namespace is accepted by dot, such as 'resize.{namespace}'.
  24. * @param {function} handler - A callback function.
  25. */
  26. on( event, handler ) {
  27. event.split( ' ' ).forEach( name => {
  28. if ( ! handlers[ name ] ) {
  29. handlers[ name ] = [];
  30. }
  31. handlers[ name ].push( handler );
  32. } );
  33. },
  34. /**
  35. * Unsubscribe the given event.
  36. *
  37. * @param {string} event - A event name.
  38. */
  39. off( event ) {
  40. event.split( ' ' ).forEach( name => delete handlers[ name ] );
  41. },
  42. /**
  43. * Emit an event.
  44. *
  45. * @param {string} event - An event name.
  46. * @param {*} args - Any number of arguments passed to handlers.
  47. */
  48. emit( event, ...args ) {
  49. each( handlers, ( callbacks, name ) => {
  50. if ( name.split( '.' )[ 0 ] === event ) {
  51. if ( callbacks ) {
  52. for ( const i in callbacks ) {
  53. callbacks[ i ]( ...args );
  54. }
  55. }
  56. }
  57. } );
  58. },
  59. };
  60. }