ti4pqq
Last Updated: February 25, 2016
·
501
· adjavaherian

Basic jQuery UI widget creation

As a front end web developer, this pattern is good to know. We're gonna use the jQuery UI widget factory to create a new widget named 'test'. Include jQuery / UI yadda yadda, put this in your pipe and smoke it.

(function($){
    $.widget('ui.test', {
        _init: function(){
            alert( this.element.html() );
        }
    });
})(jQuery);

$('#my-widget').test();

All we did was create an IIFE which takes jQuery as an argument and 'maps it to jQuery' so other libraries don't. Then, using the .widget( name [, base:optional function ], prototype {} ) method, we create a new widget with a namespace 'ui' and give it a proper name: 'test'. Our widget only implements the most basic _init functionality. (...about the underscore: its usually a private or privileged method or property, use it as written). Check the API to see what other methods are available to your new baby widget.

Stack,
Fiddle,
API