-
Notifications
You must be signed in to change notification settings - Fork 0
/
pluginify.js
75 lines (63 loc) · 2.49 KB
/
pluginify.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
/*
* This file is part of the Fxp package.
*
* (c) François Pluchino <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import $ from 'jquery';
/**
* Define the class as Jquery plugin.
*
* @param {String} pluginName The name of jquery plugin defined in $.fn
* @param {String} dataName The key name of jquery data
* @param {function} ClassName The class name
* @param {boolean} [shorthand] Check if the shorthand of jquery plugin must be added
* @param {String|null} dataApiAttr The DOM data attribute selector name to init the jquery plugin with Data API, NULL to disable
* @param {String} removeName The method name to remove the plugin data
*/
export default function(pluginName, dataName, ClassName, shorthand = false, dataApiAttr = null, removeName = 'destroy') {
let old = $.fn[pluginName];
$.fn[pluginName] = function(options = {}, ...args) {
let resFunc,
resList;
resList = this.each((i, element) => {
let $this = $(element),
data = $this.data(dataName);
if (!data) {
data = new ClassName(element, typeof options === 'object' ? options : {});
$this.data(dataName, data);
}
if (typeof options === 'string' && data) {
if (data[options]) {
resFunc = data[options].apply(data, args);
resFunc = resFunc !== data ? resFunc : undefined;
} else if (data.constructor[options]) {
resFunc = data.constructor[options].apply(data, args);
resFunc = resFunc !== data ? resFunc : undefined;
}
if (options === removeName) {
$this.removeData(dataName);
}
}
});
return 1 === resList.length && undefined !== resFunc ? resFunc : resList;
};
$.fn[pluginName].Constructor = ClassName;
// Shorthand
if(shorthand) {
$[pluginName] = (options) => $({})[pluginName](options);
}
// No conflict
$.fn[pluginName].noConflict = () => $.fn[pluginName] = old;
// Data API
if (null !== dataApiAttr) {
$(window).on('load', function () {
$(dataApiAttr).each(function () {
let $this = $(this);
$.fn[pluginName].call($this, $this.data());
});
});
}
}