-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdroplet.once.js
95 lines (84 loc) · 2.39 KB
/
droplet.once.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
91
92
93
94
95
/*!
* droplet Once v0.0.1
* @license MIT, GPL-2.0
* http://opensource.org/licenses/MIT
* http://opensource.org/licenses/GPL-2.0
*/
/**
* @class dropletOnce
* @param {NodeList} elements
* @param {String} [id="once"]
*/
function dropletOnce (elements, id) {
"use strict";
var dataId = this.checkId(id);
var filtered = Array.prototype.filter.call(elements, function (element) {
return element.getAttribute(dataId) == null;
});
filtered.map(function (element) {
element.setAttribute(dataId, "");
});
return filtered;
}
dropletOnce.prototype = {
constructor: dropletOnce,
/**
* Ensures that the given ID is valid, returning "data-drupal-once" if one is not given.
*
* @param {string} [id="once"]
* A string representing the ID to check. Defaults to `"once"`.
*
* @returns The valid ID name.
*
* @throws Error when an ID is provided, but not a string.
* @public
*/
checkId: function (id) {
"use strict";
id = id || "once";
if (typeof id !== "string") {
throw new Error("The Once id parameter must be a string");
}
return "data-drupal-" + id;
},
/**
* Removes the once data from elements, based on the given ID.
*
* @param {string} [id="once"]
* A string representing the name of the data ID which should be used when
* filtering the elements. This only filters elements that have already been
* processed by the once function. The ID should be the same ID that was
* originally passed to the once() function. Defaults to `"once"`.
*
* @example
* ``` javascript
* // Remove once data with the "changecolor" ID. The result set is the
* // elements that had their once data removed.
* dropletOnce.removeONce(document.querySelectorAll('.test' + j), 'changecolor');
* ```
*
* @see dropletOnce
* @this dropletOnce
*
* @global
* @public
*/
removeOnce: function (elements, id) {
"use strict";
Array.prototype.forEach.call(elements, function (element) {
element.removeAttribute(dropletOnce.checkId(id));
});
}
};
/**
* @class dropletOnce
* @param {NodeList} elements
* @param {String} [id="once"]
*/
dropletOnce.init = function (elements, id) {
"use strict";
return new dropletOnce(elements, id);
};
dropletOnce.checkId = dropletOnce.prototype.checkId;
dropletOnce.removeOnce = dropletOnce.prototype.removeOnce;
dropletOnce.version = "1.0.0";