zvodd
5/30/2015 - 5:00 AM

mutli_event_binder.js

// untested garbarge.
// sets on<eventname> on DOM elements to a single event handler
// that can lookup multiple events.
// maybe it works in shitty old browsers.


var EventDict = {
	/*
	// Dom Nodes can't be dictionary keys - should have used weakmap.js
	// For demonstrative purposes.
	'event_name': [{'node': <DOMNODE>, 'handlers': <Array( Functions )>}]
	*/
};

function bind_event(event_name, element, callback){
	if (typeof element.nodeType === 'undefined'){
		return;
	}

	var callback_nodelist = EventDict[event_name],
	node_entries = null;
	
	if (typeof callback_nodelist === "undefined" || callback_nodelist == null){
		EventDict[event_name] = [{'node':element, 'handlers':[callback]}];
		attach_master_event_handler();
		return;
	}else{
		node_entries = EventDict[event_name];
	}
	// find the node
	var foundnode = false;
	for (var i = 0; i < node_entries.length; i++){
		// if node found
		if (node_entries[i]['node'] === element){
			node_entries[i]['handlers'].push(callback);
			foundnode = true;
			break;
		}
	}
	// if the element is not in the event list, add it
	if (!foundnode){
		node_entries.push({'node':element, 'handlers':[callback]});
	}

	attach_master_event_handler();

	function attach_master_event_handler(){
		var dom_ev_attr = element['on'+event_name];
		if (typeof dom_ev_attr !== "undefined" && dom_ev_attr != null && dom_ev_attr !== handle_event){
			//add the old event
			// I really have no idea why I added this.
			// just guessing that the on<event> attribute can be a string sometimes?
			if (typeof dom_ev_attr === "string"){
				bind_event(event_name, element,
				function(){
				eval(dom_ev_attr);
				});
			}else{
				bind_event(event_name, element, dom_ev_attr);
			}
		}
		// Why no addEvent?   ¯\_(ツ)_/¯
		element['on'+event_name] = dom_ev_attr = function (){
			// ie 5 support is here.
			handle_event(event_name, element);
		};
	}
}

function handle_event(evtype, evelement ){

	var callback_nodelist = EventDict[evtype],
		match_el = null,
		handlers = null;
	//check EventDict for matching eventtype
	if (typeof callback_nodelist === "undefined" || callback_nodelist == null){
		//console.log("No event entry of this type in dictionary.");
		return;
	}

	for ( var ei = 0; ei < callback_nodelist.length; ei++ ){
		node = callback_nodelist[ei]['node'];
		if (node === evelement){
			match_el = node;
			handlers = callback_nodelist[ei]['handlers'];
			break;
		}
	}
	// redundant check; should raise an error
	if (typeof match_el === "undefined" || match_el == null){
		//console.log("Event entry is malformed.");
		return;
	}
	if (typeof handlers === "undefined" || handlers.length == 0){
		//console.log("No handlers exist for this node.");
		return;
	}

	for (var i = 0; i < handlers.length; i++){
		handlers[i](evelement);
	}

}