Created
August 17, 2012 12:09
-
-
Save arian/3378348 to your computer and use it in GitHub Desktop.
Multiple Event handlers idea with next()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var slice = Function.prototype.call.bind(Array.prototype.slice); | |
var forEach = Function.prototype.call.bind(Array.prototype.forEach); | |
var Event = function(event){ | |
this.event = event || window.event; | |
this.locals = {}; | |
}; | |
Event.prototype.target = function(){ | |
return this.event.target; | |
}; | |
var Nodes = function(element){ | |
this[0] = element; | |
this.length = 1; | |
}; | |
var nodes = function(element){ | |
return new Nodes(element); | |
}; | |
var stack = {}; | |
Nodes.use = function(type, fn){ | |
if (!stack[type]) stack[type] = []; | |
stack[type].push(fn); | |
}; | |
var handle = function(layers, event){ | |
var index = 0; | |
var node = this; | |
event = new Event(event); | |
var next = function(err){ | |
if (err) throw err; | |
var layer = layers[index++]; | |
if (layer) layer.call(node, event, next); | |
}; | |
next(); | |
}; | |
Nodes.prototype.on = function(type){ | |
var layers = [].concat(stack[type] || []).concat(slice(arguments, 1)); | |
console.log(layers); | |
forEach(this, function(node){ | |
node.addEventListener(type, handle.bind(node, layers)); | |
}); | |
}; | |
// usage | |
Nodes.use('click', function(event, next){ | |
this.style.color = 'red'; | |
next(); | |
}); | |
var delegate = function(event, next){ | |
var target = event.target(); | |
if (target.tagName == 'SPAN') target = target.parentNode; | |
event.locals.target = target; | |
next(); | |
}; | |
var delay = function(event, next){ | |
setTimeout(function(){ | |
next(); | |
}, 200); | |
}; | |
var thang = function(event){ | |
console.log(this, event, event.locals.target); | |
}; | |
nodes(document.getElementById('test')).on('click', delegate, delay, thang); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment