[Adept Software Development] JavaScript Events - Part 1 - Setting Events

0 views
Skip to first unread message

Paul Marrington

unread,
Aug 29, 2005, 1:09:50 AM8/29/05
to adeptr...@googlegroups.com
This is part 1 of a 3 part series.
  • Part 1: Setting Events
  • Part 2: The Event Object.
  • Part 3: A General Usable Event Manager. I've just refactored the JavaScript events system for Adept. I initially chose to implement the menu system by generating HTML rather than by building objects. Bad choice. It highlighted the operational inconsistencies between 3 completely different ways to add an event to an element.

    Three Event Addition Methods

    1. In HTML as in <a onclick="myfunc">.
    2. As an Attribute as in element.onclick = myfunc;
    3. Using the DOM Model as in element.addEventListener( "click", myfunc, false);.

    The HTML Event

    You can set an event for an element directly in the HTML using the event name preceded by "on". The code generates a function and compiles the attribute value text as the function body. This means that you are not running in the same context as when you programatically attach an event, since your code is running inside a method body. One browser inconsistency is overcome by this method: IE generates function(){yourcode} while Mozilla generates function(event){yourcode}. This allows both event types to access the event object as event even though it is passed in in Mozilla and is a global for IE. Warning: Don't use this to reference the element firing the event. It works for Mozilla, but not for IE.

    Event Attribute

    In the pre-DOM world, attributes were just fields on the HTML element. For backwards compatability they still are and always will be (for HTML anyway). So,
    element.onclick = function() { alert( "click"); }
    

     

    will work. The problem is that a single element can only have one event function per event type. This makes it difficult to produce library type code for JavaScript.

    DOM Events

    If events are set using the addEventListener() method they are stacked and all events added are fired. Perfect, except that IE (as of 6) does not support this part of the DOM.

    Summary

    So, what are the problems?
    1. Event setting that's portable across browsers does not allow more than one event per type per element.
    2. addEventListener() is not platform independent.


    --
    Posted by Paul Marrington to Adept Software Development at 8/29/2005 03:09:00 PM
Reply all
Reply to author
Forward
0 new messages