Extending widgets in Jquery UI with redefining parent methods

Darkside picture Darkside · Sep 16, 2011 · Viewed 7.4k times · Source

I try to extend UI dialog according to documentation (UI version 1.8.16):

(function($) {
    $.widget('ui.mydialog', $.extend(true, $.ui.dialog.prototype, {
        _create: function() {
            return $.Widget.prototype._create.apply(this, arguments);
        }
    }));
})(jQuery);

$(function() {
    $('div#dialog').mydialog();
});

Executing of this code causes JS error: "this.uiDialog is undefined".

And if try to override the _init() method there are no errors, but parent method call takes no effect.

I'm confused.. Which way is legal to extending for e.g. put some custom initialize code?

Answer

William Niu picture William Niu · Sep 18, 2011

I think this post would solve your question: Inherit from jQuery UI dialog and call overridden method.

In short, if you want to build a widget inheriting jQuery UI Dialog, you can do this:

(function($) {
    $.widget("ui.mydialog", $.ui.dialog, {
        _create: function() {
            $.ui.dialog.prototype._create.call(this);
        }
    });

})(jQuery);

See this in action: http://jsfiddle.net/william/RELxP/.


This tutorial will enlighten you: http://wiki.jqueryui.com/w/page/12138135/Widget%20factory. In short, $.Widget is the base widget object. Even though it has a _create function, it by default does nothing, leaving the initialisation code to the subclass. Take a look at this updated example: http://jsfiddle.net/william/RELxP/1.