-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
61 lines (49 loc) · 1.68 KB
/
index.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
/* Copyright (c) 2018 Hampus Joakim Nilsson
* Licensed via the MIT license.
**/
// Unique counter per COMPONENT that uniqueness is added to
var _globallyUniqueIdCounter = 0
function resetUniqueIds() {
_globallyUniqueIdCounter = 0
}
function injectUniqueness(component) {
var instanceId;
if (arguments.length > 1) {
instanceId = arguments[1];
if (typeof instanceId !== 'string') {
console.log('Warning: Expected string as second argument passed to `injectUniqueness`')
instanceId = '' + instanceId
}
}
// Store all state in the closure for the member functions
var _render = component.render
var _htmlIds = {}
var _uniqueIdCounter = 0
var _uniqueInstance = instanceId || ++_globallyUniqueIdCounter
// Inject the following functions into the component
component.render = function () {
_uniqueIdCounter = 0
return _render.apply(component)
}
component.nextUniqueId = function () {
++_uniqueIdCounter
return 'id-' + _uniqueInstance + '-' + _uniqueIdCounter
}
component.lastUniqueId = function () {
return 'id-' + _uniqueInstance + '-' + _uniqueIdCounter
}
component.getUniqueId = function (identifier) {
if (typeof identifier !== 'string') {
console.log('Warning: Expected string identifer passed to `getUniqueId`')
identifier = '' + identifier
}
if (!_htmlIds[identifier]) {
_htmlIds[identifier] = 'id-' + _uniqueInstance + '-' + identifier
}
return _htmlIds[identifier]
}
}
module.exports = {
resetUniqueIds: resetUniqueIds,
enableUniqueIds: injectUniqueness,
}