Instantly share code, notes, and snippets.

Embed
What would you like to do?
簡易イベント管理
!function(app){
let instance = null;
let listener = {};
let callback = {};
let nonameListener = 'event';
let nonameListenerNum = 0;
class Event{
constructor(){
if(instance) return instance;
}
// ===========================================================================
// イベントの追加
// ===========================================================================
attachEvent(name,cb){
if(callback[name]){
console.log(`'${name}' event is already defined...`);
return
}
callback[name] = cb;
listener[name] = listener[name] || {};
}
// ===========================================================================
// イベントの削除
// ===========================================================================
detachEvent(name){
if(!callback[name]) return;
delete callback[name];
delete listener[name];
}
// ===========================================================================
// リスナーの追加
// ===========================================================================
addEventListener(name,label,callback){
if(!callback){
callback = label;
label = nonameListener+nonameListenerNum;
nonameListenerNum++;
}
listener[name] = listener[name] || {};
if(listener[name][label]){
console.log(`${name} event listener '${label}' is already existed...`);
return;
}
listener[name][label] = callback;
return {event:name,label:label};
}
// ===========================================================================
// リスナーの削除
// ===========================================================================
removeEventListener(name,label){
if(!listener[name]) return
if(label) delete listener[name][label];
else delete listener[name];
}
// ===========================================================================
// イベントの発火
// ===========================================================================
dispatch(name,eventArgs = {}){
if(callback[name]){
let addArgs = callback[name](eventArgs);
addArgs = typeof addArgs === 'object' ? addArgs : {};
let keys = Object.keys(addArgs);
for(let i = 0,l = keys.length; i<l; i++){
let key = keys[i];
eventArgs[key] = addArgs[key];
}
for(let key in listener[name]) listener[name][key](eventArgs);
}
}
// ===========================================================================
// instanceの取得
// ===========================================================================
static getInstance(){
return instance;
}
}
app.class['Event'] = Event;
}(window.app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment