使用重新定义父方法在 Jquery UI 中扩展小部件

我尝试根据 documentation(UI 版本 1.8.16)扩展 UI 对话框:

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();
});

执行此代码会导致 JS 错误:this.uiDialog is undefined".

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

如果尝试重写 _init() 方法没有错误,但父方法调用无效.

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?

推荐答案

我认为这篇文章会解决你的问题:从 jQuery UI 对话框继承并调用被覆盖的方法.

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

简而言之,如果你想构建一个继承 jQuery UI Dialog 的小部件,你可以这样做:

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);

查看实际操作:http://jsfiddle.net/william/RELxP/.

本教程将启发你:http://wiki.jqueryui.com/w/page/12138135/Widget%20factory.简而言之,$.Widget 是基础小部件对象.即使它有一个 _create 函数,默认情况下它什么也不做,将初始化代码留给子类.看看这个更新的例子:http://jsfiddle.net/william/RELxP/1.

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.

相关文章