I thought it might be a good idea to add an (dom 1) event handling
module to MochiKit.
What this is about, is descibed for example in
http://www.ditchnet.org/wp/2005/04/02/6/.
Basicly, instead of writing stuff like <div onclick="foo()" id="bar">,
one adds the event via a javascript function, maybe
addEvent('bar','click',foo,false)
Possible interface (see
http://www.scottandrew.com/weblog/articles/cbs-events for background):
function addEvent(element,eventType,callbackFunction,useCapture)
function removeEvent(element,eventType,callbackFunction,useCapture)
I haven't used any of this yet (o.k., I just started playing around
with JS couple of days ago), but this seemed to me quite an important
thing to get right within a JavaScript library.
Another article somewhat related to this is
http://www.brockman.se/writing/method-references.html
If there is any interest, I'll pass along my experiences with this.
Stephan
// Start code
MochiKit.Base.bindAsEventListener = function (func, self) {
var im_func = func.im_func;
var im_self = func.im_self;
if (typeof(im_func) != 'function') {
im_func = func;
}
if (typeof(self) != 'undefined') {
im_self = self;
}
var newfunc = function (event) {
var me = arguments.callee;
var self = me.im_self;
if (!self) {
self = this;
}
return me.im_func.call(self, event || window.event);
};
newfunc.im_self = im_self;
newfunc.im_func = im_func;
return newfunc;
};
MochiKit.Base.addMethodEventListener = function (element, action, func,
self) {
if (element.addEventListener) {
element.addEventListener(action,
MochiKit.Base.bindAsEventListener(func, self), false);
} else if (element.attachEvent) {
element.attachEvent("on" + action,
MochiKit.Base.bindAsEventListener(func, self));
}
}
// End code
It's particular to my use (I just need method as event listener so I
embedded the bind in addEvent, and I don't need useCapture), but can be
adapt. Most of this code come from Rico/Scriptaculous.
Used like this :
MochiKit.Base.addMethodEventListener(MochiKit.DOM.getElement("foo"),
"mousedown", this.mouseListener, this);
Works on Firefox, IE, Konqueror.
--
Thomas
Stephan
just found this thread while looking for ways to add event handling. I
see that you don't have removeEventListener equivalent and am wondering
why ? Is it not needed in general ?
If remove needs to be added, seems that the addMethod calls need to
return the "created" function by the factory(bind call) as the caller
would need that reference to remove it from the element.