Skip to content

Instantly share code, notes, and snippets.

@chrislewis
Created September 21, 2009 19:02
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 chrislewis/190475 to your computer and use it in GitHub Desktop.
Save chrislewis/190475 to your computer and use it in GitHub Desktop.
/*
* 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