You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

62 lines
1.0 KiB

  1. define([
  2. ], function(
  3. ) {
  4. return {
  5. events: {},
  6. queue: [],
  7. on: function(event, callback) {
  8. var list = this.events[event] || (this.events[event] = []);
  9. list.push(callback);
  10. for (var i = 0; i < this.queue.length; i++) {
  11. var q = this.queue[i];
  12. if (q.event != event)
  13. continue;
  14. this.queue.splice(i, 1);
  15. i--;
  16. q.args.splice(0, 0, event);
  17. this.emit.apply(this, q.args);
  18. }
  19. return callback;
  20. },
  21. off: function(event, callback) {
  22. var list = this.events[event] || [];
  23. var lLen = list.length;
  24. for (var i = 0; i < lLen; i++) {
  25. if (list[i] == callback) {
  26. list.splice(i, 1);
  27. i--;
  28. lLen--;
  29. }
  30. }
  31. if (lLen == 0)
  32. delete this.events[event];
  33. },
  34. emit: function(event) {
  35. var args = [].slice.call(arguments, 1);
  36. var list = this.events[event];
  37. if (!list) {
  38. this.queue.push({
  39. event: event,
  40. args: args
  41. });
  42. return;
  43. }
  44. var len = list.length
  45. for (var i = 0; i < len; i++) {
  46. var l = list[i];
  47. l.apply(null, args);
  48. }
  49. }
  50. };
  51. });