Search code examples
javascripteventsprototypejs

Is there a way to get back anonymous event handlers that were registered with Event.observe in Prototype?


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?


Solution

  • 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]
      })