2011-02-13 67 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({}); 
});