mitt:极简事件监听[JavaScript] 纯文本查看 复制代码
function mitt(all/*: EventHandlerMap*/) {
all = all || Object.create(null);
return {
on(type/*: string*/, handler/*: EventHandler*/) {
(all[type] || (all[type] = [])).push(handler);
},
off(type/*: string*/, handler/*: EventHandler*/) {
if (all[type]) {
all[type].splice(all[type].indexOf(handler) >>> 0, 1);
}
},
emit(type/*: string*/, evt/*: any*/) { // * 表示订阅所有事件消息
(all[type] || []).slice().map((handler) => { handler(evt); });
(all['*'] || []).slice().map((handler) => { handler(type, evt); });
}
};
}
const m = mitt();
m.on('hello', (name) => console.log('hello ' + name));
m.emit('hello', 'world');
Vuex版[JavaScript] 纯文本查看 复制代码
/**
* Get the first item that pass the test
* by second argument function
*
* @param {Array} list
* @param {Function} f
* @return {*}
*/
export function find (list, f) {
return list.filter(f)[0]
}
/**
* Deep copy the given object considering circular structure.
* This function caches all nested objects and its copies.
* If it detects circular structure, use cached copy to avoid infinite loop.
*
* @param {*} obj
* @param {Array<Object>} cache
* @return {*}
*/
export function deepCopy (obj, cache = []) {
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
const hit = find(cache, c => c.original === obj)
if (hit) {
return hit.copy
}
const copy = Array.isArray(obj) ? [] : {}
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy
})
Object.keys(obj).forEach(key => {
copy[key] = deepCopy(obj[key], cache)
})
return copy
}