CollectingHandler.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. module.exports = CollectingHandler;
  2. function CollectingHandler(cbs){
  3. this._cbs = cbs || {};
  4. this.events = [];
  5. }
  6. var EVENTS = require("./").EVENTS;
  7. Object.keys(EVENTS).forEach(function(name){
  8. if(EVENTS[name] === 0){
  9. name = "on" + name;
  10. CollectingHandler.prototype[name] = function(){
  11. this.events.push([name]);
  12. if(this._cbs[name]) this._cbs[name]();
  13. };
  14. } else if(EVENTS[name] === 1){
  15. name = "on" + name;
  16. CollectingHandler.prototype[name] = function(a){
  17. this.events.push([name, a]);
  18. if(this._cbs[name]) this._cbs[name](a);
  19. };
  20. } else if(EVENTS[name] === 2){
  21. name = "on" + name;
  22. CollectingHandler.prototype[name] = function(a, b){
  23. this.events.push([name, a, b]);
  24. if(this._cbs[name]) this._cbs[name](a, b);
  25. };
  26. } else {
  27. throw Error("wrong number of arguments");
  28. }
  29. });
  30. CollectingHandler.prototype.onreset = function(){
  31. this.events = [];
  32. if(this._cbs.onreset) this._cbs.onreset();
  33. };
  34. CollectingHandler.prototype.restart = function(){
  35. if(this._cbs.onreset) this._cbs.onreset();
  36. for(var i = 0, len = this.events.length; i < len; i++){
  37. if(this._cbs[this.events[i][0]]){
  38. var num = this.events[i].length;
  39. if(num === 1){
  40. this._cbs[this.events[i][0]]();
  41. } else if(num === 2){
  42. this._cbs[this.events[i][0]](this.events[i][1]);
  43. } else {
  44. this._cbs[this.events[i][0]](this.events[i][1], this.events[i][2]);
  45. }
  46. }
  47. }
  48. };