JQuery UI Widget Boilerplate
I’m always writing this stuff out again and again so I thought I’d save the most useful stuff for copying and pasting.
The widget
$.widget("ui.aWidgetName", { options: { requiredOptionOne: null, requiredOptionTwo: null, optionalOptionOne: null, $thisElement: null }, _init: function () { var self = this, $thisElement = $(self.element); //NOTE: Useful for refining JQuery selectors ie. $(".something", $thisElement) if (!!self.options.optionOne && !!self.options.optionTwo) { //NOTE: do widgety stuff, but only if required options have been set } else { return; } } });
Accessing an option after init
//NOTE: get $(".widgetElementSelector").aWidgetName("options", "optionalOptionOne") //NOTE: note the 's' on 'options' //NOTE: set $(".widgetElementSelector").aWidgetName("options", "optionalOptionOne", "aValue")
Custom callbacks
//NOTE: a point where you want to trigger event self._trigger("anEventName"); //NOTE: when creating a widget $(".widgetElementSelector").aWidgetName({ anEventName: function (event) { //NOTE: stuff to do when the event happens } }); //NOTE: binding after widget init //NOTE: the concatinated widget/event name is converted to lower case $(":data(aWidgetName)").bind("awidgetnameaneventname", function () { $(".marketing-video-container object").css({ "width": "0", "height": "0" }); })