114 lines
2.5 KiB
JavaScript
114 lines
2.5 KiB
JavaScript
/**
|
|
Copyright (c) 2016 hustcc http://www.atool.org/
|
|
License: MIT
|
|
https://github.com/hustcc/onfire.js
|
|
**/
|
|
|
|
const __onfireEvents = {}
|
|
let __cnt = 0 // event counter
|
|
|
|
const string_str = 'string'
|
|
const function_str = 'function'
|
|
const hasOwnKey = Function.call.bind(Object.hasOwnProperty)
|
|
const slice = Function.call.bind(Array.prototype.slice)
|
|
|
|
function _bind(eventName, callback, is_one, context) {
|
|
if (typeof eventName !== string_str || typeof callback !== function_str) {
|
|
throw new Error('args: ' + string_str + ', ' + function_str + '')
|
|
}
|
|
|
|
if (!hasOwnKey(__onfireEvents, eventName)) {
|
|
__onfireEvents[eventName] = {}
|
|
}
|
|
|
|
__onfireEvents[eventName][++__cnt] = [callback, is_one, context]
|
|
return [eventName, __cnt]
|
|
}
|
|
|
|
function _each(obj, callback) {
|
|
for (const key in obj) {
|
|
if (hasOwnKey(obj, key)) callback(key, obj[key])
|
|
}
|
|
}
|
|
|
|
function on(eventName, callback, context) {
|
|
return _bind(eventName, callback, 0, context)
|
|
}
|
|
|
|
function one(eventName, callback, context) {
|
|
return _bind(eventName, callback, 1, context)
|
|
}
|
|
|
|
function _fire_func(eventName, args) {
|
|
if (hasOwnKey(__onfireEvents, eventName)) {
|
|
_each(__onfireEvents[eventName], (key, item) => {
|
|
item[0].apply(item[2], args) // do the function
|
|
if (item[1]) delete __onfireEvents[eventName][key] // when is one, delete it after trigger
|
|
})
|
|
}
|
|
}
|
|
|
|
function fire(eventName) {
|
|
// fire events
|
|
const args = slice(arguments, 1)
|
|
setTimeout(() => {
|
|
_fire_func(eventName, args)
|
|
})
|
|
}
|
|
|
|
function fireSync(eventName) {
|
|
_fire_func(eventName, slice(arguments, 1))
|
|
}
|
|
|
|
function un(event) {
|
|
let eventName,
|
|
key,
|
|
r = false
|
|
const type = typeof event
|
|
|
|
if (type === string_str) {
|
|
// cancel the event name if exist
|
|
if (hasOwnKey(__onfireEvents, event)) {
|
|
delete __onfireEvents[event]
|
|
return true
|
|
}
|
|
return false
|
|
} else if (type === 'object') {
|
|
eventName = event[0]
|
|
key = event[1]
|
|
|
|
if (hasOwnKey(__onfireEvents, eventName) && hasOwnKey(__onfireEvents[eventName], key)) {
|
|
delete __onfireEvents[eventName][key]
|
|
return true
|
|
}
|
|
return false
|
|
} else if (type === function_str) {
|
|
_each(__onfireEvents, (key1, item1) => {
|
|
_each(item1, (key2, item2) => {
|
|
if (item2[0] === event) {
|
|
delete __onfireEvents[key1][key2]
|
|
r = true
|
|
}
|
|
})
|
|
})
|
|
return r
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
function clear() {
|
|
for (const key in __onfireEvents) {
|
|
delete __onfireEvents[key]
|
|
}
|
|
}
|
|
|
|
export default {
|
|
on,
|
|
one,
|
|
un,
|
|
fire,
|
|
fireSync,
|
|
clear,
|
|
}
|