/** * Minimal jQuery Widget Example * Author: Andreas Schaefer * * Usage: * *
* * ... * * $('#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([ '
', '

My Cool Widget

', '', '
' ].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 [ '
  • ', '', '#' + index + ' : ' + item.title, '', '
  • ' ].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]); } });