如何获取jQuery UI小部件的名称?

3
我需要一种方法来读取jQuery UI小部件的名称。我已经将dialog小部件子类化为两个子类,myDialog1myDialog2。我创建了一个destroyDialog函数来销毁当前活动的对话框。应该有一种方法来确定小部件实例的名称。
我想要做的事情是这样的:
var destroyDialog = function() {
    activeDialog[activeDialog.widgetName]("destroy");
}

但我没有找到获取小部件名称的方法。目前,我使用丑陋的嵌套try-catch语句。

var destroyDialog = function() {
        try {
            activeDialog.dialog("destroy");
        }
        catch (e) {
            try {
                activeDialog.myDialog1("destroy");
            }
            catch (e) {
                activeDialog.myDialog2("destroy");
            }
        }
    }
2个回答

3
您可以通过以下方式获取并使用小部件名称:
activeDialog.data("widgetName");

...正如tdmartin所提到的那样。 因此:

activeDialog[activeDialog.data("widgetName")]("destroy");

然而,为了解决这个问题,我个人写了一个插件,可以让你调用一个小部件方法,而无需知道小部件的类型。 这将使您能够执行以下操作:

activeDialog.callWidgetMethod('destroy');

本插件依赖于您使用jQuery UI 1.11+。如果您使用的是<1.11版本,则可以去掉"如果该小部件没有这个方法则跳过"检查,但缺点是如果尝试调用小部件没有的方法,则会出现错误。

插件代码:

jQuery.fn.callWidgetMethod = function () {
    var args = arguments;
    var result = null;
    if(!this || !this.length) 
        return this;

    this.each(function (i,o) {
        var compClass = $(this).data("widgetName");
        var func = $(this)[compClass];
        // Skip this element if it does not appear to be an initialised jQuery widget
        if(!compClass || !func)
            return true;

        // Skip this widget if it does not have the method (the name of which will be in args[0])
        // This relies on the 'instance' method provided in jQuery UI 1.11
        if(args.length>1 && !$(this)[compClass]("instance")[args[0]])
            return true;

        result = func.apply($(this),args);
    });

    if(this.length>1) 
        return this;
    else 
        return result;
};

2
如果您标准化命名空间,就可以使用正则表达式来匹配存储小部件实例的变量名称(即小部件的名称),该名称由$().data()方法返回。
for (i in $(<your element>).data() ) {
    if (i.match(/dialog/)) {
        $(<your element>).data(i).destroy();
    }
}

谢谢你的帮助,但是我的两个“子类”小部件不是$.ui.dialog的实例,而是它们自己的小部件,继承了dialog的方法。$(this).dialog()会抛出一个错误 - 它需要$(this).myDialog1()或$(this).myDialog2(),这就是为什么我需要知道如何获取小部件名称的原因。 - Tanner Semerad
哦,对不起,我没有理解你在做什么。如果你运行 $(<your element>).data(); 它将返回一个带有所有jqueryUi特定数据的对象,其中一个元素是你的部件名称(如果你的部件名称中有一个点,如activeDialogMyDialog2,则为驼峰式)。你可以以一种易于获取它们的方式命名你的部件。 - tdmartin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接