EventMgr.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. class EventMgr{
  2. constructor() {
  3. console.log('EventMgr初始化');
  4. this.events = {};
  5. }
  6. //注册事件
  7. registerEvent(eventName, func, target){
  8. if(eventName==null || !func || !target){
  9. return;
  10. }
  11. if(!this.events[eventName]){
  12. this.events[eventName] = [];
  13. }
  14. this.events[eventName].push({'target': target, 'func': func});
  15. }
  16. //移除事件
  17. removeEvent(eventName, func, target){
  18. if(eventName==null || !func || !target){
  19. return;
  20. }
  21. let handlers = this.events[eventName];
  22. if(!handlers) return;
  23. for(let i=0; i< handlers.length; i++){
  24. if(handlers[i] && handlers[i].func == func && handlers[i].target == target){
  25. handlers[i] = undefined;
  26. break;
  27. }
  28. }
  29. }
  30. //移除整个事件
  31. clearEvent(eventName){
  32. let handlers = this.events[eventName];
  33. if(!handlers) return;
  34. for(let i=0; i < handlers.length; i++){
  35. handlers[i] = undefined;
  36. }
  37. }
  38. //分发事件
  39. postEvent(eventName, params){
  40. let handlers = this.events[eventName];
  41. if(!handlers) return;
  42. for(let i=0; i< handlers.length; i++){
  43. if(handlers[i]){
  44. try{
  45. handlers[i].func.call(handlers[i].target, params);
  46. }catch(error){
  47. console.log(error.message);
  48. console.log(error.stack.toString());
  49. }
  50. }
  51. }
  52. }
  53. }
  54. let instance = null;
  55. EventMgr.getInstance = function(){
  56. if(!instance){
  57. instance = new EventMgr();
  58. }
  59. return instance;
  60. }
  61. module.exports = EventMgr;