Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // event-wrapper.js
- (function(angular, factory) {
- 'use strict';
- if (typeof define === 'function' && define.amd) {
- define([
- 'angular'
- ], function(angular) {
- return factory(angular);
- });
- } else {
- return factory(angular);
- }
- }(window.angular, function(angular) {
- 'use strict';
- angular.module('eventWrapper', [])
- .service('eventWrapper', function() {
- var _listeners = {},
- TYPE_ONE = "one";
- return {
- on: function (eventName, callback) {
- _listeners[eventName] || (_listeners[eventName] = []);
- _listeners[eventName].push({
- action: callback
- });
- },
- one: function (eventName, callback) {
- _listeners[eventName] || (_listeners[eventName] = []);
- _listeners[eventName].push({
- type: TYPE_ONE,
- action: callback
- });
- },
- emit: function (eventName) {
- var chain = _listeners[eventName],
- len = chain.length,
- i, item, action;
- // 逆序遍历,以免删除数组导致问题
- for (i = len; item = chain[i]; i--) {
- action = item.action
- if (typeof action === 'function') {
- try {
- action();
- } catch (e) {
- "console" in window && console.error(e);
- }
- }
- if(item.type === TYPE_ONE)
- chain.splice(i, 1);
- }
- }
- };
- })
- }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement