-
Notifications
You must be signed in to change notification settings - Fork 15
/
jquery-plugin-boilerplate.js
90 lines (75 loc) · 2.09 KB
/
jquery-plugin-boilerplate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* A jQuery plugin boilerplate.
* Author: Jonathan Nicol @f6design
*/
;(function($) {
var pluginName = 'demoplugin';
function Plugin(element, options) {
var el = element;
var $el = $(element);
options = $.extend({}, $.fn[pluginName].defaults, options);
function init() {
// Add any initialization logic here...
hook('onInit');
}
function fooPublic() {
// Code goes here...
}
function option (key, val) {
if (val) {
options[key] = val;
} else {
return options[key];
}
}
function destroy() {
$el.each(function() {
var el = this;
var $el = $(this);
// Add code to restore the element to its original state...
hook('onDestroy');
$el.removeData('plugin_' + pluginName);
});
}
function hook(hookName) {
if (options[hookName] !== undefined) {
options[hookName].call(el);
}
}
init();
return {
option: option,
destroy: destroy,
fooPublic: fooPublic
};
}
$.fn[pluginName] = function(options) {
if (typeof arguments[0] === 'string') {
var methodName = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var returnVal;
this.each(function() {
if ($.data(this, 'plugin_' + pluginName) && typeof $.data(this, 'plugin_' + pluginName)[methodName] === 'function') {
returnVal = $.data(this, 'plugin_' + pluginName)[methodName].apply(this, args);
} else {
throw new Error('Method ' + methodName + ' does not exist on jQuery.' + pluginName);
}
});
if (returnVal !== undefined){
return returnVal;
} else {
return this;
}
} else if (typeof options === "object" || !options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
}
};
$.fn[pluginName].defaults = {
onInit: function() {},
onDestroy: function() {}
};
})(jQuery);