Skip to content

Instantly share code, notes, and snippets.

@sacrifs
Last active December 10, 2015 22:18
Show Gist options
  • Save sacrifs/4500520 to your computer and use it in GitHub Desktop.
Save sacrifs/4500520 to your computer and use it in GitHub Desktop.
カスタムイベントをJSで使う。
/**
* spiffieldCustomEvent
*
* @license MIT License http://www.opensource.org/licenses/mit-license.php
* @author sacrifs http://labs.spiffield.net/
* @update 2013/01/11
*
* var obj = document.createElement("object");
* spfdCustomEvent.addListener(obj, "loadComp", function(e){alert("loadComplete!")});
* spfdCustomEvent.dispatch(obj, "loadComp");
*/
var spfdCustomEvent = spfdCustomEvent || {};
(function(){
var _handlerFuncList = {};
/**
* addListener
* addEventListener / attachEvent
* @param target : DOMElement
* @param type : String
* @param func : Function
*/
addListener = function(target, type, func){
if(target.addEventListener){
target.addEventListener(type, func, false);
}
else if(target.attachEvent){
if(target.parentNode != document){
target.style.display = "none";
document.appendChild(target);
}
_handlerFuncList[type] = func;
if(_handlerFuncList.length == 1){
target.attachEvent("ondataavailable", handleFuncIE);
}
}
},
/**
* removeListener
* removeEventListener / detachEvent
* @param target : DOMElement
* @param type : String
* @param func : Function
*/
removeListener = function(target, type, func){
if(target.removeEventListener){
target.removeEventListener(type, func, false);
}
else if(target.detachEvent){
delete _handlerFuncList[type];
if(_handlerFuncList.length == 0){
target.detachEvent("ondataavailable", handleFuncIE);
}
}
},
/**
* handleFuncIE
*
* @param e : Event
*/
handleFuncIE = function(e){
var func = _handlerFuncList[e.datatype];
if(func){func(e);}
},
/**
* dispatch
* dispatchEvent / fireEvent
* @param target : DOMElement
* @param type : String
* @param data : Object
*/
dispatch = function(target, type, data){
var ev;
if(document.createEvent){
ev = document.createEvent("Event");
ev.initEvent(type, true, true);
ev.datatype = type;
ev.data = data;
target.dispatchEvent(ev);
}
else if(document.createEventObject){
ev = document.createEventObject();
ev.datatype = type;
ev.data = data;
target.fireEvent("ondataavailable", ev);
}
}
//public
spfdCustomEvent.addListener = addListener;
spfdCustomEvent.removeListener = removeListener;
spfdCustomEvent.dispatch = dispatch;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment