views:

97

answers:

3

Interfacing with legacy code, and I've got something like this:

Event.observe(some_form, 'submit', [some anonymous function])

I'd like to grab that anonymous event handler back out, is there an easy way to do that in Prototype?

A: 

If you actually want access to the handler, no, there's no easy way. You can of course stopObserving all prototype initiated handlers for an event type, but I don't think that's what you're looking for.

Myles
A: 

If there aren't too many other listeners on some_form + submit-event or you control all others you could get at it with

var boundSubmitEvents = some_form.getStorage().get('prototype_event_registry').get('submit');
boundSubmitEvents.each(function(wrapper){
    //do with wrapper.handler whatever
})

btw. what do you mean with

grab that anonymous event handler back out

jitter
+3  A: 

It depends on the version of Prototype. From a more general answer I wrote previously:

  • version 1.5.x:

    // inspect
    Event.observers.each(function(item) {
        if(item[0] == some_form && item[1] == 'submit') {
            alert(item[2]) // [some anonymous function]
        }
    })
    
  • versions 1.6 to 1.6.0.3, inclusive (got very difficult here)

    // inspect. "_eventId" is for < 1.6.0.3 while 
    // "_prototypeEventID" was introduced in 1.6.0.3
    var submitEvents = Event.cache[some_form._eventId || (some_form._prototypeEventID || [])[0]].submit;
    submitEvents.each(function(wrapper){
        alert(wrapper.handler) // [some anonymous function]
    })
    
  • [Current] version 1.6.1 (little better)

    // inspect
    var submitEvents = some_form.getStorage().get('prototype_event_registry').get('submit');
    submitEvents.each(function(wrapper){
        alert(wrapper.handler) // [some anonymous function]
    })
    
Crescent Fresh
Exactly what I was looking for, thanks. Looks like we're using 1.6.0.3 but I'm getting that Event.cache is undefined =(
gct
@gct: `Event.cache` is set by virtue of simply including 1.6.0.3: (http://prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js). My guess is the `submitEvents` variable is what is undefined. This can happen when there simply haven't been any `submit` handlers bound **with Prototype** (read: *not* including `onsubmit="..."`) *at the point you are checking*. Need to see more code to help further.
Crescent Fresh