Extending widgets in Jquery UI with redefining parent methods

偶尔善良 提交于 2019-12-22 01:14:40

问题


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?


回答1:


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.




回答2:


From jQuery 1.9 and on, if you want to add functionality to a widget and don't want to replace the existing function, after you do your code call the parent method. To do this, instead of what William Niu suggests, you can simply do this:

_create: function()
{
    // Custom code here

    // Call the _create method of the widget
    this._super();
}

This applies to all existing methods. (eg _setOption, _trigger etc)




回答3:


I posted a simple example of extending a jQueryUI Dialog using the Widget factory.

http://jsfiddle.net/Artistan/jWUGZ/

This example extends a dialog to create a simple loading modal.



来源:https://stackoverflow.com/questions/7450791/extending-widgets-in-jquery-ui-with-redefining-parent-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!