I'm working on a plugin using the ui widget factory. With a basic JQuery plugin, I can access the selector used by doing something like this...
$.fn.pluginname = function(){
var thisWorks = this.selector;
};
However, when I use the widget factory, the selected element is accessed through the 'this.element' property, and 'this.element.selector' does not work the same way as in my first example. Anyone have a nice way around this? I'm looking through the widget factory source code on GitHub, but I haven't been able to find anything yet.
The trick is that after the widget factory has completed creating your widget, it is essentially just a normal plugin afterwards. That means you can further extend it.
The idea is to save the original function, replace it with a custom function and make it pass the selector through. This code can be anywhere after the widget factory and before you use your object the first time. Just put it in your plugin file after calling $.widget()
.
The name of the widget in this example is 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 makes sure that this.selector
is passed through as a named option. Now you can access it anywhere within your factory by referencing this.options.selector
.
As an added plus, we didn't need to hack any jQuery UI code.
Just my couple cents... here is working JSFiddle example based on DarthJDG's answer... Probably someone will need it.
$(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({});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With