简体   繁体   中英

Can't trigger self-made Event.prototype

I have this prototype function ->

Event.prototype.eventPreventDefault = function () {
    this.preventDefault ? this.preventDefault() : this.returnValue = false;
}

I call from code by doing this ->

$element.click(function (evt) {
        evt.eventPreventDefault();
}

but I get

Uncaught TypeError: undefined is not a function

What do I do wrong? Thanks!

Event objects created by jQuery (and passed into event handlers) are not children of native Events ( 'prefer composition over inheritance' principle ). They have their own set of methods (set on jQuery.Event.prototype ):

jQuery.Event.prototype = {
    constructor: jQuery.Event,
    isDefaultPrevented: returnFalse,
    isPropagationStopped: returnFalse,
    isImmediatePropagationStopped: returnFalse,

    preventDefault: function() {
        var e = this.originalEvent;

        this.isDefaultPrevented = returnTrue;

        if ( e && e.preventDefault ) {
            e.preventDefault();
        }
    },
    stopPropagation: function() {
        var e = this.originalEvent;

        this.isPropagationStopped = returnTrue;

        if ( e && e.stopPropagation ) {
            e.stopPropagation();
        }
    },
    // ... and so on.
};

As you see, these methods usually call the same-named methods of the original Event (stored in jQuery.Event instance's originalEvent property). The point is, jQuery.Event doesn't have Event.prototype in its inheritance chain, hence any modification of the latter is destined to have no effect on the former.

The bottom line: to extend Events passed into jQuery event handlers, extend jQuery.Event.prototype instead of Event.prototype .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM