Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to extend JQueryEventObject in TypeScript

I've only just started with Typescript but I'm wondering if it is possible to extend the JQueryEventObject with a new method - I'd like to add a cancel method that sets the event to stop bubbling and propagating.

If my understanding is correct, there is no way to do this using TypeScript because the JQueryEventObject is merely an interface created to provide an intellisense of what is available on the event object provided to an event. However, I may be wrong and if someone has got a solution, then I'd appreciate someone sharing that with me.

like image 312
Anupheaus Avatar asked Nov 28 '25 14:11

Anupheaus


1 Answers

You are correct that the typescript definition is an interface, however, you can extend it, and you can also extend the runtime to add the new function. There are two things that need to be done:

  1. make typescript aware of the new function
  2. make the new function available at runtime inside jQuery

Here is a code sample that does both:

// PatchJquery.ts
// Include the generated .js file for this, after jQuery, in some html file.

/// <reference path="typedef/jquery/jquery.d.ts" />

// Runtime patch: Assume jQuery is already defined in the global scope 
// and patch its Event prototype.
jQuery.Event.prototype.cancel = function() {
    console.log("Someone wants me to cancel this event!",this);
}

// Define the extended typescript interface
interface ExtJQueryEventObject extends JQueryEventObject {
    cancel():void;
}

// Test
$(function() {
    var body:JQuery = $("body");
    body.on('click', (e:ExtJQueryEventObject) => {
        e.cancel();
    });
});

Note that if you wanted, say, an actual click event, you would need to define an extended interface for JQueryMouseEventObject. You would need to do this for all of the different JQuery event types. Alternatively, you could just modify jquery.d.ts to add your new function to BaseJQueryEventObject.

(BTW, jQuery has stopPropagation() and stopImmediatePropagation(), which might do what you want already)

like image 154
mushin Avatar answered Nov 30 '25 03:11

mushin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!