Created
September 21, 2009 19:02
-
-
Save chrislewis/190475 to your computer and use it in GitHub Desktop.
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
/* | |
* Extension that makes it easy to convert an array to a "hash" | |
* (a bland JSON object), given an array of desired keys. | |
*/ | |
Array.prototype.toObject = function(keys) { | |
var obj = {}; | |
for(var i = 0; i < keys.length; i++) { | |
obj[keys[i]] = this[i]; | |
} | |
return obj; | |
} | |
/* | |
* An object for building an object of handler methods, which can | |
* can then be added via Element.addMethods. Example result: | |
* | |
* { | |
* mousedown: function(element, fn) { | |
* element = $(element); | |
* element.observe("mousedown", fn.bind(element)); | |
* return element; | |
* }, | |
* mouseup: function(element, fn) { | |
* element = $(element); | |
* element.observe("mouseup", fn.bind(element)); | |
* return element; | |
* } | |
* } | |
*/ | |
var InlineHandlers = { | |
events: "mousedown,mouseup".split(","), | |
build: function() { | |
// Much cleaner with the array extension. | |
return this.events.map(this._buildObservationMethod).toObject(this.events); | |
}, | |
_buildObservationMethod: function(name) { | |
return function(element, fn) { | |
element = $(element); | |
element.observe(name, fn.bind(element)); | |
return element; | |
}; | |
} | |
}; | |
Element.addMethods(InlineHandlers.build()); | |
// Now we have jQuery-style event registration. | |
$("aLink") | |
.mousedown(function(e) { | |
this.update("DOWN - " + e); | |
}) | |
.mouseup(function(e) { | |
this.update("UP - " + e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment