tags:

views:

40

answers:

1

Hi all,

Could any one explain me the difference between IE and DOM Standard event model in simple terms ?

Thanks.

A: 

They mostly do the same thing*, but you just have to determine which one to use by which browser your client uses. Dustin Diaz created this namespace to easily determine which event model to use:

var Event = {
    add: function() {
        if (window.addEventListener) {
            return function(el, type, fn) {
                DOM.$(el).addEventListener(type, fn, false);
            };
        } else if (window.attachEvent) {
            return function(el, type, fn) {
                var f = function() {
                    fn.call(DOM.$(el), window.event);
                };
                DOM.$(el).attachEvent('on' + type, f);
            };
        }
    }()
};

* - I say "mostly" the same thing, because you'll notice that the DOM addEventListenter takes an extra parameter at the end, which indicates whether to use event capturing (true) or bubbling (false). Events fire from the root element down the DOM tree or from the source element up the DOM tree, so this flag determines what the event.stopPropagation function does. Capturing means that the element can call event.stopPropagation to stop event propagation to its child element. Bubbling means that the browser can call event.stopPropagation to stop event propagation to its parent element.

palswim
Your `Event.remove` implementation won't work in IE. It is not trivial to get it working, and I suspect that's why Dustin left it out of his implementation in the first place.
Crescent Fresh
@Crescent Fresh: Yeah, I just copied and pasted the code. I removed the problematic part and left the part that is helpful for explanation.
palswim
Your explanation for the third parameter for `addEventListener` is incorrect: you seem to be implying that it governs whether the event will propagate from its original target or not, whereas in fact it has no effect on *whether* the event propagates, just how it does so: setting it `true` means the event progresses from the document root down through the tree until it reaches the target; when `false` it does the opposite, i.e. starting from the event's target and progressing (bubbling) up the tree to the document root. http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-capture
Tim Down
@Tim Down: My explanation wasn't very clear; see edit.
palswim