Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom method to UI dialog plugin

I am using jQuery's UI dialogs and I want to add a custom method.

Basically when my dialog has a class of 'working', it has a loading overlay in it. I am trying to write some global application jQuery so that when any dialog closes, it removes the class 'working'.

I'm not really sure what I'm doing but this is what I have so far:

(function ($) {

    // BIND TO DIALOG CLOSE EVENT
    $('.ui-dialog').live('dialogclose', function() {
        $(this).dialog('cancelWorking');
    });

    // CUSTOM METHOD
    $.fn.dialog.cancelWorking = function() {
        $(this).removeClass('working');
    };

}(jQuery));

As you can see I'm not really sure how to call the cancelWorking method of a dialog, and I'm not sure if I've even defined the method properly.

like image 362
BadHorsie Avatar asked Dec 27 '22 15:12

BadHorsie


1 Answers

As mentioned in my comment, you can inherit from a plugin and extend its methods.

(function($,undefined) {

    $.widget('ui.mydialog', $.ui.dialog,{
        test : function() { alert('works') },
    });

    $.extend($.ui.mydialog,{version:'v0.1'});
 })(jQuery);

To use it simply:

$('.selector').mydialog({modal:true}); //Create (same as a dialog)

$('.selector').mydialog('test');  //Call extended method 

This pattern allows you to add additional input options, methods, events, etc. as well as overload or extend the functions supplied in the parent plugin.

Should also mention that this is nice because you can still use the regular plugin without modifications elsewhere in your UI.

like image 106
jyore Avatar answered Jan 05 '23 07:01

jyore