Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing .selector within a JQuery UI Widget

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.

like image 795
Brandon Joyce Avatar asked Feb 13 '11 19:02

Brandon Joyce


2 Answers

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.

like image 68
DarthJDG Avatar answered Sep 26 '22 00:09

DarthJDG


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({});
});
like image 37
Mr. Pumpkin Avatar answered Sep 27 '22 00:09

Mr. Pumpkin