Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we create a custom jquery plugin using typescript?

I need to use a jquery custom plugin in my application and how can i create a custom jquery plugin using typescript. I have googled a lot and i just got below links

http://typescript.codeplex.com/discussions/398401

Define a custom jQuery UI widget in TypeScript

The above links uses plain javascript code, however javascript code will work in typescript but the issue with this is i can't use typescript classes with in this plugin. Is there any way to use typescript classes with in jquery plugin or else is there any other way to create jquery plugin in typescript.

Any suggestions should be appreciated.

like image 424
Karthi Keyan Avatar asked Oct 25 '13 09:10

Karthi Keyan


2 Answers

There's very little difference between using JavaScript and Typescript when creating a plugin. You'll likely want to grab the jQuery definition for TypeScript from here first and add it to your project (or include it on the command line, etc., depending on your development environment).

Then, just write the plugin and use whatever classes and existing code you want. The example below doesn't do anything other than demonstrate that it's hardly any different from the original JavaScript plugin techniques.

(function($) {
    $.fn.myPlugin = function() {
        // do something
        return this;
    };

    $.fn.myEachPlugin = function(options)  {
        var settings: any = $.extend({
            color: "#ffff00"
        }, options);

        return this.each(function() {
            // do something ...
        });
    };

})(jQuery);
like image 156
WiredPrairie Avatar answered Oct 31 '22 18:10

WiredPrairie


To expand on WiredPrairie's answer, here's a full typescript plugin:

export interface MyOptions {

}

// plugin definition
$.fn.myPlugin = function(this: JQuery, options: MyOptions): JQuery {
    return this.each(function (this: HTMLElement): void {
        // do something
    });
}

// make the plugin available outside this file
declare global {
    interface JQuery {
        myPlugin(options: MyOptions): this;
    }
}
like image 44
Métoule Avatar answered Oct 31 '22 16:10

Métoule