-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.parseDataAttributes.js
More file actions
70 lines (62 loc) · 2.24 KB
/
jquery.parseDataAttributes.js
File metadata and controls
70 lines (62 loc) · 2.24 KB
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
/**
* Plugin that converts data-params in elements to an
* array of params to use it for loading plugins without
* the need to add js to every view you have.
*
* @author Òscar Casajuana <elboletaire@underave.net>
* @license Apache-2.0
* @copyright Òscar Casajuana 2014
* @version 0.1
*/
;(function($){
// dashed-toCamelCase
String.prototype.camelCase = function() {
return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace(/-|_/, '');});
};
var DataAttrParser = function($this, options) {
var defaults = {
prefix : false,
params : {}
};
options = $.extend(true, defaults, options);
if (!options.prefix) {
return;
}
options.prefix = 'data-' + options.prefix + '-';
if ($this.attr(options.prefix + 'disable')) {
return;
}
$($this[0].attributes).each(function() {
// Set any param found in data- attributes
var prefix_regex = new RegExp('^' + options.prefix);
if (this.nodeName.match(prefix_regex)) {
var param = this.nodeName.replace(prefix_regex, ''),
value = this.value;
// Due to DOM limitations we need to set CamelCased vars as dashed-vars and they're replaced here
if (param.match(/(\-[a-z])/g)) {
param = param.camelCase();
}
if (typeof value === 'string') {
if (value === 'true' || value === 'false') {
value = Boolean(value);
}
}
if (!isNaN(value) && typeof value !== 'boolean') {
value = parseInt(value, 10);
}
options.params[param] = value;
}
});
if (typeof options.callback === 'function') {
options.callback($this, options.params);
}
};
$.fn.parseDataAttributes = function(options, callback) {
return this.each(function() {
if (typeof callback === 'function') {
options.callback = callback;
}
return new DataAttrParser($(this), options);
});
};
})(jQuery);