prettify

baseline

Javascript event handling (all browsers except ie7)

Now that IE9 supports addEventListener and IE7's market share is diminishing (goodle analytics tell me that ie7 and older is at 14% and loses 2% per month).
If we can support ie8 (@31%) we can forever forget attachEvent.
That mean we support all current browsers but not ie7 and older.
ie8.js:
/*@cc_on
  @if (@_jscript_version >= 9)     // >ie9=========================================
  @elif (@_jscript_version == 5.8) // ie8=========================================
if (!document.addEventListener && document.attachEvent){
    HTMLDocument.prototype.addEventListener =
    Element.prototype.addEventListener =
    Window.prototype.addEventListener = function (type, fCallback, capture) {
        var sEvent = "on" + type;
        if (capture) {
            throw new Error("IE does not support capture");
        }
        var that = this;
        this.attachEvent(sEvent, function (e) {
            Object.defineProperty(e, 'currentTarget', {
                get: function () { return that; }
            });
            Object.defineProperty(e, 'eventPhase', {
                get: function () {
                    return (e.srcElement == that) ? 2 : 3; // "AT_TARGET" = 2, "BUBBLING_PHASE" = 3
                }
            });
            var time = new Date();
            Object.defineProperty(e, 'timeStamp', {
                get: function () { return time; }
            });
            fCallback.call(that, e);
        });
    };
    Object.defineProperty(Event.prototype, 'target', {
        get: function () {return this.srcElement;}
    });
    Event.prototype.stopPropagation = function () {this.cancelBubble = true;};
    Event.prototype.preventDefault = function () {this.returnValue = false;};

    HTMLDocument.prototype.removeEventListener =
    Element.prototype.removeEventListener =
    Window.prototype.removeEventListener = function (type, fCallback) {
        this.detachEvent("on"+type,fCallback);
    };
}
  //@elif (@_jscript_version == 5.7 && window.XMLHttpRequest) //ie7
  @else        //ie older =================================================
    alert("This version of IE is not supported! Use at least:\n"+
    "IE 8.0\n"+"Firefox 4\n"+"Chrome 6.0\n"+"Opera 10\n"+"Safari 4");
  @end
@*/

No comments:

Post a Comment