views:

398

answers:

2

Say I add events to an object using either addEventListener or attachEvent (depending on the browser); is it possible to later invoke those events programmatically?

The events handlers are added/removed using an object like this:

var Event = {
    add: function(obj,type,fn) {
     if (obj.attachEvent) {
      obj.attachEvent('on'+type,fn);
     } else {
      obj.addEventListener(type,fn,false);
        }
    },
    remove: function(obj,type,fn) {
     if (obj.detachEvent) {
      obj.detachEvent('on'+type,fn);
     } else {
      obj.removeEventListener(type,fn,false);
        }
    }
}

Or do I need to store copies of each handler and just add an Event.invoke(...) function?

Edit: Also, jQuery is not an option :D

+1  A: 

Can you not create functions that do the work required, run those from the events then run those same functions later when required?

Mark Redman
+6  A: 

As usual, you have to do it one way for Internet Explorer, and the correct way for everything else ;-)

For IE:

document.getElementById("thing_with_mouseover_handler").fireEvent("onmouseover");

See the MSDN library for more info.

For the real browsers:

var event = document.createEvent("MouseEvent");
event.initMouseEvent("mouseover", true, true, window);
document.getElementById("thing_with_mouseover_handler").dispatchEvent(event);

Note that, although the second, standards-based approach seems more long-winded, it is also considerably more flexible: check the documentation, starting with the Mozilla DOM Event Reference at https://developer.mozilla.org/en/DOM/event

Although only tangentially related to what you're trying to do (it's related to custom events, rather than normal ones) Dean Edwards has some example code at http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ that may be worth a look.

NickFitz