开发者

I would like comments on an approch to wrap widgets in jQuery

When using jQueryUi widgets (dialog, datepicker etc) I always wonder if there would be better to wrap the widgets in some kind of wrapper class. Here is one way to do this, but I'm not sure if this is good practice.

Please comment

CODE

Small plugin for $ that wraps 'dialog'.

//Widget Wrapper plugin POC.
//Should be extended to support all Methods on all Widgets in jQueryUI   
(function ($) {
    $.fn.ww = function (uiWidgetName, options) {
    if (this.length == 1) {
        return new wrappers[uiWidgetName](this[0], options);
    }
}


var wrappers= {};

wrappers.dialog = function (element, options) {
    var 开发者_如何学编程theWidget = $(element);
    theWidget.dialog(options);

    this.open = function () {
        theWidget.dialog('open');
    }
    this.close = function () {
        theWidget.dialog('close');
    }
  }

} (jQuery))

This could be used like this

var a = $("#WrapperTest").ww('dialog',{ autoOpen: false });            
a.open();


Well, actually, the functions added to the $.fn namespace by jQuery UI ($.fn.dialog() in your case) are already wrappers around each widget's methods.

It looks like you want to implement some kind of "reverse-wrapper" around the existing dialog() wrapper in order to be able to access the widget's methods directly. Adding another layer of overhead is not necessary, as you only have to invoke the widget's constructor directly, specifying the widget options and the target element:

var dialogWidget = new $.ui.dialog({
    autoOpen: false
}, $("#WrapperTest")[0]);

Then you can do things like:

dialogWidget.open();
dialogWidget.close();
dialogWidget.option("autoOpen", !dialogWidget.option("autoOpen"));
// and so on.

If you have created a dialog the "usual" way (through $.fn.dialog()) and you want to to obtain a reference to its widget instance further down the line, you can fetch it from the element's data using the widget's name as the key:

$("#WrapperTest").dialog({
    autoOpen: false
});

var dialogWidget = $("#WrapperTest").data("dialog");
dialogWidget.open();

You can test the code above in this fiddle.

Update: From jQuery UI 1.9 onwards, the data() key becomes the widget's fully qualified name, with dots replaced by dashes. Therefore, the code above becomes:

var dialogWidget = $("#WrapperTest").data("ui-dialog");
dialogWidget.open();

Using the unqualified name is still supported in 1.9 but is deprecated, and support will be dropped in 1.10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜