Created
October 3, 2012 16:51
-
-
Save bryanforbes/3828256 to your computer and use it in GitHub Desktop.
data-* bindings for Dojo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define([ | |
'exports', | |
'dojo/has', | |
'dojo/dom' | |
], function(exports, has, dom){ | |
has.add('dom-dataset', function(global, document, element){ | |
return typeof element.dataset === 'object' && !!element.dataset; | |
}); | |
var ccRE = /(-+)([^-])/g; | |
function camelCase(attribute){ | |
return attribute.replace(ccRE, function(substr, dashes, letter){ | |
return dashes.slice(1) + letter.toUpperCase(); | |
}); | |
} | |
var dccRE = /[A-Z]/g; | |
function deCamelCase(attribute){ | |
return attribute.replace(dccRE, function(uppercase){ | |
return '-' + uppercase.toLowerCase(); | |
}); | |
} | |
if(has('dom-dataset')){ | |
exports.get = function(node, attribute){ | |
node = dom.byId(node); | |
if(attribute){ | |
return node.dataset[camelCase(attribute)]; | |
}else{ | |
var data = {}; | |
for(var name in node.dataset){ | |
data[name] = node.dataset[name]; | |
} | |
return data; | |
} | |
}; | |
exports.set = function(node, attribute, value){ | |
node = dom.byId(node); | |
if(typeof attribute === 'object' && attribute){ | |
for(var name in attribute){ | |
exports.set(node, name, attribute[name]); | |
} | |
}else{ | |
node.dataset[camelCase(attribute)] = value || null; | |
} | |
}; | |
}else{ | |
var dataRE = /^data-/; | |
exports.get = function(node, attribute){ | |
node = dom.byId(node); | |
if(attribute){ | |
return node.getAttribute('data-' + deCamelCase(attribute)); | |
}else{ | |
var data = {}; | |
for(var i=0; attribute=node.attributes[i]; i++){ | |
if(dataRE.test(attribute.name)){ | |
data[camelCase(attribute.name.replace(dataRE, ''))] = attribute.value; | |
} | |
} | |
return data; | |
} | |
}; | |
exports.set = function(node, attribute, value){ | |
node = dom.byId(node); | |
if(typeof attribute === 'object' && attribute){ | |
for(var name in attribute){ | |
exports.set(node, name, attribute[name]); | |
} | |
}else{ | |
node.setAttribute('data-' + deCamelCase(attribute), '' + value); | |
} | |
}; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment