Advertisement
Guest User

Untitled

a guest
May 3rd, 2015
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1.  
  2. // event-wrapper.js
  3.  
  4. (function(angular, factory) {
  5. 'use strict';
  6.  
  7. if (typeof define === 'function' && define.amd) {
  8. define([
  9. 'angular'
  10. ], function(angular) {
  11. return factory(angular);
  12. });
  13. } else {
  14. return factory(angular);
  15. }
  16. }(window.angular, function(angular) {
  17. 'use strict';
  18. angular.module('eventWrapper', [])
  19. .service('eventWrapper', function() {
  20. var _listeners = {},
  21. TYPE_ONE = "one";
  22.  
  23. return {
  24. on: function (eventName, callback) {
  25. _listeners[eventName] || (_listeners[eventName] = []);
  26. _listeners[eventName].push({
  27. action: callback
  28. });
  29. },
  30. one: function (eventName, callback) {
  31. _listeners[eventName] || (_listeners[eventName] = []);
  32. _listeners[eventName].push({
  33. type: TYPE_ONE,
  34. action: callback
  35. });
  36. },
  37. emit: function (eventName) {
  38. var chain = _listeners[eventName],
  39. len = chain.length,
  40. i, item, action;
  41. // 逆序遍历,以免删除数组导致问题
  42. for (i = len; item = chain[i]; i--) {
  43. action = item.action
  44. if (typeof action === 'function') {
  45. try {
  46. action();
  47. } catch (e) {
  48. "console" in window && console.error(e);
  49. }
  50. }
  51. if(item.type === TYPE_ONE)
  52. chain.splice(i, 1);
  53. }
  54. }
  55. };
  56. })
  57. }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement