123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- // 发布订阅,事件模型
- var Event = (function () {
- var _default = 'default';
- var _shift = Array.prototype.shift;
- var _unshift = Array.prototype.unshift;
- function createEvent() {
- var namespaceCache = {}
- function _listen(cache, key, fn) {
- if (cache[key]) {
- cache[key].push(fn)
- } else {
- cache[key] = [fn]
- }
- }
- function _trigger() {
- var args = arguments
- return new Promise(function(resolve) {
- setTimeout(function () {
- var cache = _shift.call(args);
- var key = _shift.call(args);
- var stack = cache[key]
- if (!stack || stack.length === 0) return;
- stack.forEach(function (fn) {
- fn.apply(this, args)
- })
- resolve(stack);
- }, 100)
- })
- }
- function _remove(cache, key, fn) {
- var stack = cache[key]
- if (!stack || stack.length === 0) return
- if (fn) {
- for (var i = stack.length; i >= 0; i--) {
- if (stack[i] === fn) {
- stack.splice(i, 1)
- }
- }
- } else {
- stack.length = 0
- }
- }
- function _create(namespace) {
- namespace = namespace || _default
- if (namespaceCache[namespace]) {
- return namespaceCache[namespace]
- }
- var cache = {}
- var ret = {
- listen: function (key, fn) {
- _listen(cache, key, fn)
- },
- once: function (key, fn) {
- fn.__once = true
- _listen(cache, key, fn)
- },
- remove: function (key, fn) {
- _remove(cache, key, fn)
- },
- trigger: function () {
- _unshift.call(arguments, cache)
- _trigger.apply(this, arguments).then(function (stack) {
- if (stack) {
- for (var i = stack.length; i >= 0; i--) {
- if (stack[i] && stack[i].__once) {
- stack.splice(i, 1)
- }
- }
- }
- })
- }
- }
- namespaceCache[namespace] = ret;
- return ret
- }
- return {
- create: _create,
- once: function () {
- this.create().once.apply(this, arguments)
- },
- listen: function () {
- this.create().listen.apply(this, arguments)
- },
- remove: function () {
- this.create().remove.apply(this, arguments)
- },
- trigger: function () {
- this.create().trigger.apply(this, arguments)
- }
- }
- }
- return createEvent()
- })();
|