3 Copyright 2013 Marco Braak
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
22 SimpleWidget = (function() {
23 SimpleWidget.prototype.defaults = {};
25 function SimpleWidget(el, options) {
27 this.options = $.extend({}, this.defaults, options);
30 SimpleWidget.prototype.destroy = function() {
31 return this._deinit();
34 SimpleWidget.prototype._init = function() {
38 SimpleWidget.prototype._deinit = function() {
42 SimpleWidget.register = function(widget_class, widget_name) {
43 var callFunction, createWidget, destroyWidget, getDataKey, getWidgetData;
44 getDataKey = function() {
45 return "simple_widget_" + widget_name;
47 getWidgetData = function(el, data_key) {
49 widget = $.data(el, data_key);
50 if (widget && (widget instanceof SimpleWidget)) {
56 createWidget = function($el, options) {
57 var data_key, el, existing_widget, i, len, widget;
58 data_key = getDataKey();
59 for (i = 0, len = $el.length; i < len; i++) {
61 existing_widget = getWidgetData(el, data_key);
62 if (!existing_widget) {
63 widget = new widget_class(el, options);
64 if (!$.data(el, data_key)) {
65 $.data(el, data_key, widget);
72 destroyWidget = function($el) {
73 var data_key, el, i, len, results, widget;
74 data_key = getDataKey();
76 for (i = 0, len = $el.length; i < len; i++) {
78 widget = getWidgetData(el, data_key);
82 results.push($.removeData(el, data_key));
86 callFunction = function($el, function_name, args) {
87 var el, i, len, result, widget, widget_function;
89 for (i = 0, len = $el.length; i < len; i++) {
91 widget = $.data(el, getDataKey());
92 if (widget && (widget instanceof SimpleWidget)) {
93 widget_function = widget[function_name];
94 if (widget_function && (typeof widget_function === 'function')) {
95 result = widget_function.apply(widget, args);
101 return $.fn[widget_name] = function() {
102 var $el, args, argument1, function_name, options;
103 argument1 = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
105 if (argument1 === void 0 || typeof argument1 === 'object') {
107 return createWidget($el, options);
108 } else if (typeof argument1 === 'string' && argument1[0] !== '_') {
109 function_name = argument1;
110 if (function_name === 'destroy') {
111 return destroyWidget($el);
112 } else if (function_name === 'get_widget_class') {
115 return callFunction($el, function_name, args);
125 module.exports = SimpleWidget;