在 JQuery UI Widget 中访问 .selector

5

我正在开发一个插件,使用UI小部件工厂。通过基本的JQuery插件,我可以像这样访问所使用的选择器...

$.fn.pluginname = function(){
    var thisWorks = this.selector;
};

然而,当我使用小部件工厂时,所选元素通过“this.element”属性进行访问,“this.element.selector”与我的第一个示例不同。 有没有好的方法解决这个问题? 我正在GitHub上查看小部件工厂源代码,但我还没有找到任何东西。

3个回答

5

技巧在于,小部件工厂完成创建小部件后,它基本上只是一个普通的插件。这意味着您可以进一步扩展它。

思路是保存原始函数,用自定义函数替换它,并使其通过选择器传递。此代码可以放置在小部件工厂之后,在您第一次使用对象之前的任何位置。只需在调用$.widget()之后将其放入插件文件中即可。

此示例中小部件的名称为test

// Save the original factory function in a variable
var testFactory = $.fn.test;

// Replace the function with our own implementation
$.fn.test = function(obj){
    // Add the selector property to the options
    $.extend(obj, { selector: this.selector });

    // Run the original factory function with proper context and arguments
    return testFactory.apply(this,arguments);
};

这样可以确保this.selector作为一个命名选项被传递。现在,您可以通过引用this.options.selector在工厂内的任何地方访问它。

另外一个好处是,我们不需要修改任何jQuery UI代码。


太棒了。从没想过可以这样做。我需要尝试一下我的参数,但看起来应该能正常工作。谢谢! - Brandon Joyce
如果我只修改(duckpunching)其中一个 widgets 方法,例如 tooltip 的关闭方法,并且需要访问原始选择器,我该如何做?这可能吗?这是一个不起作用的示例:http://jsfiddle.net/corydorning/9grH5/ - CoryDorning
通过上述原则,我能够解决它,尽管我不得不覆盖我正在修补的小部件的原型选项。代码片段在这里:https://gist.github.com/4445666 - CoryDorning

1

这只是我的一点建议... 这里有一个基于DarthJDG答案的JSFiddle示例... 可能有人会需要它。

$(function () {
    $.widget("test.testwidget", {
        _create: function () {
            this.element.text('Selector: ' + this.options.selector)
        },
    });
}(jQuery));

// Save the original factory function in a variable
var testFactory = $.fn.testwidget;

// Replace the function with our own implementation
$.fn.testwidget = function(obj){
    // Add the selector property to the options
    $.extend(obj, { selector: this.selector });

    // Run the original factory function with proper context and arguments
    return testFactory.apply(this,arguments);
};

$(document).ready(function() {
    $('#test').testwidget({});
    $('.test').testwidget({});
});

-1

也可以简单地使用

this.selector =  '#'+this.element.attr('id');

通常在_create方法中。 当然,这需要您的小部件的每个实例都有一个唯一的ID,通常应该这样做。

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