Skip to content

Instantly share code, notes, and snippets.

@5509
Created April 5, 2011 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5509/904063 to your computer and use it in GitHub Desktop.
Save 5509/904063 to your computer and use it in GitHub Desktop.
巡り巡ってElement.prototypeを断念。。namespace使ってbind、unbindできる(IE8以下を除く)
/*
* bind, unbind
*
* @author : nori(norimanai@gmail.com)
* @copyright : 5509(http://5509.me/)
* @license : The MIT License
* @modified : 2011-04-09 01:30
*
* HOW TO USE
* bind event : bind(elm, type, func) or bind(elm, {})
* bind event.name : bind(elm, type.name, func)
* unbind all events : unbind(elm)
* unbind events(type) : unbind(elm, type)
* unbind event.name : unbind(elm, type.name)
*/
YOURNAMESPACE.bind = function() {
var i, _a = arguments;
if ( typeof _a[1] === "object" ) {
for ( i in _a[1] ) {
bindFunc(i, _a[1][i]);
}
} else {
bindFunc(_a[1], _a[2]);
}
function bindFunc(type, func) {
var i;
type = type.split(" ");
for ( i = 0, l = type.length; i < l; i++ ) {
if ( type[i].indexOf(".") !== -1 ) {
type[i] = type[i].split(".");
_a[0]["bindedNamed"] = _a[0]["bindedNamed"] || {};
_a[0]["bindedNamed"][type[i][0]] = _a[0]["bindedNamed"][type[i][0]] || {};
_a[0]["bindedNamed"][type[i][0]][type[i][1]] = func;
_a[0].addEventListener(type[i][0], func, false);
} else {
_a[0]["binded"] = _a[0]["binded"] || {};
_a[0]["binded"][type] = _a[0]["binded"][type] || [];
_a[0]["binded"][type][_a[0]["binded"][type].length] = func;
_a[0].addEventListener(type[i], func, false);
}
}
}
}
YOURNAMESPACE.unbind = function(elm, type) {
var i = 0, c, d, bindedTypes, bindedEvents, bindedNamedEvents;
if ( !type ) {
if ( elm["binded"] ) {
bindedTypes = elm["binded"];
for ( c in bindedTypes ) {
bindedEvents = bindedTypes[c];
while ( bindedEvents[i] ) {
elm.removeEventListener(c, bindedEvents[i], false);
bindedEvents.splice(i, i + 1);
}
}
}
bindedNamedEvents = elm["bindedNamed"];
if ( !bindedNamedEvents ) return false;
for ( c in bindedNamedEvents ) {
for ( d in bindedNamedEvents[c] ) {
elm.removeEventListener(c, bindedNamedEvents[c][d], false);
}
delete bindedNamedEvents[c];
}
} else
if ( type.indexOf(".") !== -1 ) {
type = type.split(".");
elm.removeEventListener(type[0], elm["bindedNamed"][type[0]][type[1]], false);
} else {
if ( elm["binded"] && elm["binded"][type] ) {
bindedEvents = elm["binded"][type];
while ( bindedEvents[i] ) {
elm.removeEventListener(type, bindedEvents[i], false);
bindedEvents.splice(i, i + 1);
}
}
bindedNamedEvents = elm["bindedNamed"][type];
if ( !bindedNamedEvents ) return false;
for ( c in bindedNamedEvents ) {
elm.removeEventListener(type, bindedNamedEvents[c], false);
}
delete bindedNamedEvents;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment