2011-02-13 104 views
5

我正在使用ui widget factory的插件。有了一个基本的jQuery插件,我可以访问由做这样的事情使用的选择...在JQuery UI小部件中访问.selector

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

然而,当我使用的部件工厂,所选择的元素通过“this.element属性来访问,和'this.element.selector'在我的第一个例子中的工作方式不同。任何人都有一个很好的解决方法呢?我正在浏览GitHub上的Widget工厂源代码,但我还没有找到任何东西。

回答

5

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

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

+0

太棒了。从来没有想过这样做。我需要玩弄我正在做的事情的论点,但看起来它会工作得很好。谢谢! – 2011-05-26 18:08:38

-1

另外,也可以简单地使用

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

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

1

只是我的夫妇美分...这里工作JSFiddle基于DarthJDG的答案的例子...可能有人会需要它。

$(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({}); 
});