Created
January 10, 2018 07:01
-
-
Save CaptainLiao/3bf0cf4f812b1f20769179ff9a60880d to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* EventBus 对象解决页面间的传值问题,在需要传值的页面引入这个文件 | |
* | |
* 更新:9-29 | |
* tigger 后自动注销事件,不需要手动管理 | |
* 更新:10-20 | |
* 支持发布-订阅、订阅-发布两种模式 | |
* listen 第三个参数用于控制是否触发cache中的方法(为true开启订阅-发布模式) | |
*/ | |
let EventBus = {}; | |
Object.defineProperties(EventBus, { | |
'cached': { | |
value: {} | |
}, | |
'handlers': { | |
value: {} | |
}, | |
'listen': { | |
get() { | |
return (event, ...options) => { | |
let args = options[0] | |
// 默认不使用cache。(缺省 undefined) | |
let isCallCache = options[1]; | |
try { | |
if (typeof args === 'function') { | |
this._listen(event, args, isCallCache); | |
} else { | |
this._listen(event, args[event].bind(args), isCallCache) | |
} | |
} catch (e) { | |
throw new Error(`${event} is not a function`) | |
} | |
} | |
} | |
}, | |
'_listen': { | |
get() { | |
return (event, fn, isCallCache) => { | |
let handlers = this.handlers | |
handlers[event] = fn | |
if (this.cached[event] && isCallCache) { | |
fn.apply(null, this.cached[event]) | |
delete this.cached[event] | |
} | |
} | |
} | |
}, | |
'remove': { | |
get() { | |
return (event, fn) => { | |
let handlers = this.handlers[event] | |
let cachedEvent = this.cached[event] | |
if (!fn) { | |
delete this.handlers[event] | |
delete this.cached[event] | |
return | |
} | |
for (let i = 0, len = handlers.length; i < len; i++) { | |
if (handlers[i] === fn) { | |
handlers.splice(i, 1) | |
cachedEvent.splice(i, 1) | |
break | |
} | |
} | |
} | |
} | |
}, | |
'trigger': { | |
get() { | |
return (event, ...options) => { | |
let handlers = this.handlers[event] | |
if (handlers) { | |
handlers.apply(null, options) | |
delete this.handlers[event] | |
} | |
this.cached[event] = options | |
} | |
} | |
} | |
}) | |
export default EventBus |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment