Skip to content

Instantly share code, notes, and snippets.

@AndiSHFR
Created October 21, 2019 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndiSHFR/a676a8bbb52a300a8f80b019d4710e62 to your computer and use it in GitHub Desktop.
Save AndiSHFR/a676a8bbb52a300a8f80b019d4710e62 to your computer and use it in GitHub Desktop.
Basic jQuery Widget Example
/**
* Minimal jQuery Widget Example
* Author: Andreas Schaefer <asc@schaefer-it.net>
*
* Usage:
*
* <div id="myCoolWidget"></div>
*
* ...
*
* $('#myCoolWidget').myCoolWidget({
* debug: true,
* limit: 5,
* select: function(event, element) { console && console.log('SELECT:', element); },
* error: function(event, err) { console && console.log('ERROR:', err); }
* });
*
* setTimeout(function() {
* var myCoolWidget = $('#myElement').myCoolWidget().data();
* myCoolWidget.reload();
* }, 30000);
*
*/
$.widget("MyNameSpace.myCoolWidget", {
version: '01.00.001',
options: {
debug: false,
api: 'https://jsonplaceholder.typicode.com/todos/',
limit: 20,
select: function(data) {},
error: function(err) {
console && console.log(err);
}
},
items: [],
_debug: function(args_) {
var widgetName = this.widgetName;
if (this.options.debug && console) {
var args = [].slice.call(arguments);
args.unshift('** ' + widgetName + ' | ');
console.log.apply(null, args);
}
},
_create: function() {
this._debug('Started:', this);
this.element.append([
'<div>',
'<h4>My Cool Widget</h4>',
'<ul></ul>',
'</div>'
].join(''));
this.element.find('ul').on('click', 'a', $.proxy(this._select, this));
this.element.addClass('my-cool-widget').data('reload', $.proxy(this._reload, this));
this._reload();
},
_destroy: function () {
this.items = [];
this.removeClass('my-cool-widget');
this.element.empty();
},
_setOption: function (key, value) {
this.options[key] = value;
this._update();
},
_raiseError: function(jqXHR, textStatus, errorThrown) {
this._trigger('error', null, new Error('Error ' + textStatus + ': ' + errorThrown));
},
_update: function() {
var li = $.map(this.items, function(item, index) {
return [
'<li>',
'<a href="#' + item.id + '">',
'#' + index + ' : ' + item.title,
'</a>',
'</li>'
].join('');
});
this.element.find('ul').empty().append(li.join(''));
},
_clear: function() {
this.items = [];
},
_reload: function() {
this._debug('Will reload...');
$.ajax({
method: 'GET',
url: this.options.api,
dataType: 'json',
data: {
limit: 3
},
success: $.proxy(function(data) {
this._debug('Response data:', data);
this.items = (data || []).slice(0, this.options.limit);
this._update();
}, this),
error: $.proxy(this._raiseError, this)
});
},
_select: function(event) {
event.preventDefault();
var
id = $(event.target).attr('href').substring(1),
item = $.grep(this.items, function(d, n) {
return (id == d.id);
})[0];
item && this._trigger('select', null, [item]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment