jQuery UI
Widgets
by Ryan Morris
HTML
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.11/jquery.mousewheel.min.js"></script>
<div id="main">
<h1>Hi</h1>
<p>This is some <em>body</em>.</p>
</div>
JavaScript
$().ready(function(){
// A basic jQuery plugin
$.fn.highlight = function(options) {
options = $.extend({
color: "blue"
}, options);
$(this).css({
color: options.color
});
return this;
};
$("#main h1").highlight();
// A basic jQueryUI Widget
$.widget("custom.highlight", {
options: {
color: "red"
},
_create: function() {
this.element.css({
color: this.options.color
});
},
// public methods
getColor: function() {
return this.options.color;
},
setColor: function(color) {
this.options.color = color;
// refactor me! (refresh)
this._create();
this._someInternalChange();
},
// private methods defined with _
_myHelper: function() {
// some private behavior
},
// can add callbacks so user can
// react to plugin events/changes
_someInternalChange: function() {
this._trigger(
// name of callback
"internalchange",
// jQuery event, if applicable
null,
// event data
{
arbitrary: 5
}
);
}
});
// 1.
//$("#main h1").highlight();
/*
// 2.
// Pass public method name to invoke methods on the widget (keeps jquery ns clean)
$("#main h1").highlight();
$("#main h1").highlight("getColor");
$("#main h1").highlight("setColor", "orange");
/**/
/*
// 3.
// Callbacks
$("#main h1").highlight({
internalchange: function(e, data) {
console.log("I changed");
...