Observer.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function Observer() {
  2. this.listeners = {};
  3. }
  4. Observer.prototype.listeners = null;
  5. Observer.prototype.addListener = function(type, callback, thisObj) {
  6. if(this.hasListener(type, callback, thisObj) !== -1) {
  7. return;
  8. }
  9. if(!(type in this.listeners)) {
  10. this.listeners[type] = [];
  11. }
  12. var arr = this.listeners[type];
  13. arr.push({func:callback, thisObj:thisObj});
  14. };
  15. Observer.prototype.hasListener = function(type, callback, thisObj) {
  16. if(!(type in this.listeners)) {
  17. return -1;
  18. }
  19. var arr = this.listeners[type];
  20. var len = arr.length;
  21. for(var i = 0; i < len; i ++) {
  22. if(arr[i].func === callback && arr[i].thisObj === thisObj) {
  23. return i;
  24. }
  25. }
  26. return -1;
  27. }
  28. Observer.prototype.removeListener = function(type, callback, thisObj) {
  29. var pos = this.hasListener(type, callback, thisObj);
  30. if(pos === -1) {
  31. return;
  32. }
  33. this.listeners[type].splice(pos, 1);
  34. }
  35. Observer.prototype.sendNotify = function(type, notice) {
  36. if(!(type in this.listeners)) {
  37. return;
  38. }
  39. var arr = this.listeners[type];
  40. var len = arr.length;
  41. for(var i = 0; i < len; i ++) {
  42. if(!arr[i]) {
  43. arr.splice(i,1);
  44. len --;
  45. i--;
  46. continue
  47. }
  48. if(arr[i].thisObj) {
  49. arr[i].func.apply(arr[i].thisObj, [type,notice]);
  50. if(arr.length != len) {
  51. len = arr.length;
  52. i --;
  53. }
  54. }
  55. }
  56. }