EventTarget()

1111

  1. var EventTarget = function() {
  2. this.listeners = {};
  3. };
  4. EventTarget.prototype.listeners = null;
  5. EventTarget.prototype.addEventListener = function(type, callback) {
  6. if(!(type in this.listeners)) {
  7. this.listeners[type] = [];
  8. }
  9. this.listeners[type].push(callback);
  10. };
  11. EventTarget.prototype.removeEventListener = function(type, callback) {
  12. if(!(type in this.listeners)) {
  13. return;
  14. }
  15. var stack = this.listeners[type];
  16. for(var i = 0, l = stack.length; i < l; i++) {
  17. if(stack[i] === callback){
  18. stack.splice(i, 1);
  19. return this.removeEventListener(type, callback);
  20. }
  21. }
  22. };
  23. EventTarget.prototype.dispatchEvent = function(event) {
  24. if(!(event.type in this.listeners)) {
  25. return;
  26. }
  27. var stack = this.listeners[event.type];
  28. event.target = this;
  29. for(var i = 0, l = stack.length; i < l; i++) {
  30. stack[i].call(this, event);
  31. }
  32. };