【问题标题】:Accessing .selector within a JQuery UI Widget在 JQuery UI Widget 中访问 .selector
【发布时间】:2011-02-13 19:40:31
【问题描述】:

我正在使用ui widget factory 开发一个插件。使用基本的 JQuery 插件,我可以通过执行类似操作来访问使用的选择器...

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

但是,当我使用小部件工厂时,通过“this.element”属性访问所选元素,并且“this.element.selector”的工作方式与我的第一个示例不同。有人有一个很好的方法吗?我正在查看 GitHub 上的小部件工厂源代码,但我还没有找到任何东西。

【问题讨论】:

    标签: jquery jquery-ui


    【解决方案1】:

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

    想法是保存原始函数,将其替换为自定义函数并使其通过选择器。此代码可以在小部件工厂之后和您第一次使用对象之前的任何位置。调用$.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 代码。

    【讨论】:

    • 太棒了。从来没有想过这样做。我需要为我正在做的事情争论不休,但它似乎会很好地工作。谢谢!
    • 如果我只是修改(duckpunching)其中一种小部件方法,例如工具提示的关闭方法并且需要访问原始选择器,我将如何做到这一点。这可能吗?这是一个无效的示例:jsfiddle.net/corydorning/9grH5
    • 能够使用上面的原理解决这个问题,尽管我必须覆盖我正在修补的小部件的原型选项。要点在这里:gist.github.com/4445666
    【解决方案2】:

    只是我的几分钱...这是基于 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({});
    });
    

    【讨论】:

      【解决方案3】:

      也可以简单的使用

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

      通常在 _create 方法中。当然,这要求您的小部件的每个实例都有一个唯一的 id,无论如何它通常都应该这样做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-05
        • 2021-01-14
        • 1970-01-01
        相关资源
        最近更新 更多