Safe add additional methods to a existing inline event handler

Discussion in 'JavaScript' started by Addininth, Sep 26, 2007.

  1. #1
    I have a page code like this:

    ..
    ..
    <head>
    <script>
    function addSafeListener(objeto, listener){
           var oldEvent = (objeto.onclick) ? objeto.onclick : function () {};
                   var modifiedEventContents = function(){
                           var returnValue = eval(listener)();
                           if(returnValue != false) returnValue = oldEvent();
                           return returnValue;
                   }
           object.onclick = eval(modifiedEventContents );
    }
    
    var behaviour_01 = function(){
           alert('First Add!!!!!!');
           var seguimos = confirm('Continue?');
           return seguimos;
    }
    
    function funcionchorrada(){
           var seguimos = confirm('Follow to the next page?');
           return seguimos;
    }
    
    window.onload = function(){
           addSafeListener(document.getElementById('hookMe'), 'behaviour_01');
    }
    </script>
    </head>
    
    <body>
      <a href="otherpage.html" id="hookMe" onclick="funcionchorrada()
    ">click on me</a>
    </body>
    ..
    ..
    
    Code (markup):
    If the "behaviour_01" method returns false the code does not continue
    to execute the old inline eventHandler (i.e. funcionchorrada()), if it
    returns true it continues. This functions OK.

    But, and that is the problem, if the method "funcionchorrada()"
    returns some valor (perhaps "false" to prevent the default behaviour
    of the <a> tag) this valor is NOT returned.

    Yesterday using alerts to debugging and today reading the mozilla
    developer page I found the answer. Inline eventHandlers although are
    typed in this manner:

    
                onclick="funcionchorrada() "
    
    Code (markup):
    Internally have this structure:

    
                function onclick(event) {
                     funcionchorrada();
                }
    
    Code (markup):
    So if the "funcionchorrada();" method returns something, this valor is
    lost cause no one stores it or comand it to "return". Currently I only
    found a solution to this, type manually a "return" before the method
    called in the inline eventHandler, so it would look like this:

    
                onclick="return funcionchorrada() "
    
    Code (markup):
    But this solution is not valid in large websites with lots on inline
    eventHandlers or in code generated dinamically like the one generated
    by Ruby.

    So, finally, this is my question:

    How Can I obtain the valor returned by the inline event handler?

    Thanks in advance,

    Antonio
     
    Addininth, Sep 26, 2007 IP