Skip to content

Instantly share code, notes, and snippets.

@zhang6464
Created March 19, 2015 03:28
Show Gist options
  • Save zhang6464/9f4389e2f6f6d7bf9177 to your computer and use it in GitHub Desktop.
Save zhang6464/9f4389e2f6f6d7bf9177 to your computer and use it in GitHub Desktop.
event-wrapper.js
// 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);
}
}
};
})
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment