Created
March 19, 2015 03:28
-
-
Save zhang6464/9f4389e2f6f6d7bf9177 to your computer and use it in GitHub Desktop.
event-wrapper.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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