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

时间:2014-01-06 22:27:28

标签: javascript jquery jquery-ui widget

我需要一种方法来读取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 个答案:

答案 0 :(得分:2)

如果您对命名空间进行标准化,则可以使用正则表达式来匹配$().data()方法返回的存储窗口小部件实例的变量名称(窗口小部件的名称)。

for (i in $(<your element>).data() ) {
    if (i.match(/dialog/)) {
        $(<your element>).data(i).destroy();
    }
}

答案 1 :(得分:2)

您可以使用

获取小部件名称(并使用它)
activeDialog.data("widgetName");

...如tdmartin所指。因此:

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

但是为了亲自解决这个问题,我编写了一个插件,允许您在不知道小部件的类型的情况下调用小部件方法。这将允许您:

activeDialog.callWidgetMethod('destroy');

它依赖于您使用jQuery UI 1.11+。如果您使用&lt; 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;
};