SitePoint Sponsor

User Tag List

Results 1 to 9 of 9
  1. #1
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Safe add additional methods to a existing inline event handler

    I have a page code like this:

    Code:
    ..
    ..
    <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>
    ..
    ..
    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() "

    Internally have this structure:

    function onclick(event) {
    funcionchorrada();
    }

    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() "

    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
    Last edited by Addininth; Sep 26, 2007 at 02:07. Reason: add apropiate code tags

  2. #2
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you have control over the code, I would recommend, that you use event-registration instead of event-handlers. See: http://www.quirksmode.org/js/events_advanced.html

  3. #3
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I know these methods. But I don&#180;t have control over the inline event handlers that may (or not may) be in the code.

    The code is generated by a Ruby application and it inserts inline event handlers where it needs them. So I have to use this JS code.

    Antonio

  4. #4
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I was checking this out...it seems that in IE event handlers can return values and they are used by the object that called the handler - but in Moz this does not happen.

    This example will block the link click in IE but Firefox ignores it and merrily goes on its way:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    var test = false;
    
    function doClick() {
    	return test;
    }	
    
    function setupEvents() {
    	var obj = document.getElementById("somelink");
    	if (obj.addEventListener) {
    		//alert("Moz");
    		obj.addEventListener("click", doClick, false);
    	} else if (obj.attachEvent) {
    		//alert("IE");
    		obj.attachEvent("onclick", doClick);
    	}
    }
    
    window.onload = setupEvents;
    </script>
    </head>
    <body>
    	<a href="http://www.sitepoint.com" id="somelink">Click me</a>
    </body>
    </html>

  5. #5
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could write a wrapper, which looks to see if there is an existing legacy style eventhandler. If there is, it should be removed, and wrapped in a registration style instead. Something like this:
    Code:
    connect = function(element, event, handler) {
      if (element["on" + event]) {
        var oldHandler = element["on" + event];
        element["on" + event] = null;
        connect(element, event, oldHandler);
      }
      if (element.addEventListener) { // w3c
        element.addEventListener(event, function(e) {
          if (!handler()) {
            e.stopPropagation();
          }
        }, false);
      } else if (element.attachEvent) { // IE
        element.attachEvent("on" + event, function() {
          var e = window.event;
          if (!handler()) {
            e.cancelBubble = true;
          }
        });
      }
    }
    But instead of writing stuff like that on your own, you should do your self a favour, and use a library, which already has that done for you. Personally, I prefer Mochikit, but there are plenty of alternatives.

  6. #6
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Truly thanks for your help. I would investigate you code to see if it can help with my problem.

    About your "use a library" saying...Sure I could use one. And surely I would spent less time doing the same things o even better ones, but If I did such thing I would finish my days without truly know JS, only this or those library...

    And first of all I love to throw my free time to the trash can!!! (It's a joke!)

    Again thanks.

    A.-

  7. #7
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Something occurred to me today based on the code I posted above, not sure if it helps:

    http://www.sitepoint.com/forums/show...87&postcount=2

  8. #8
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry jim, but your code does not function properly. Here it is:

    Code:
    <script type="text/javascript">
    function Validate(event) {
    	var thereturn = confirm("Hit OK to return true, Cancel to return false");
    	if (event) {
    		// mozilla
    		if (!thereturn) {
    			event.preventDefault();
    		}
    	} else {
    		return !thereturn;
    	}
    }
    
    window.onload = function () {
    	document.getElementById("thesubmit").onclick = Validate;
    	alert(document.getElementById("thesubmit").onclick);
    }
    </script>
    </head>
    <body>
    <form method="post" action="nextpage.php">
    	<input id="thesubmit" type='submit' />
    </form>
    </body>
    </html>
    I made to it a few changes. First, I set an alert after the listener asignation so we can saw which is the content of document.getElementById("thesubmit").onclick. Second I change the else branch of the IF so now always return false (so it would prevent the default behaviour of the form..i.e. the submit).

    If you check the code in a browser you could see that it does not prevent nothing, cause the validate method not return correctly any valor. If you change the asignation and type:
    Code:
    document.getElementById("thesubmit").onclick = return Validate;
    It will do.

    A.-

  9. #9
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry, Im not sure what you're trying to do then.

    The code I posted was supposed to prevent the form submission when you click "cancel" and allow it to submit when you click "ok", while not being explicitly set to use "return". I tested it in IE6, IE7 and FF2 - and it does what I intended.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •