Skip to content

Instantly share code, notes, and snippets.

@bryanforbes
Created October 3, 2012 16:51
Show Gist options
  • Save bryanforbes/3828256 to your computer and use it in GitHub Desktop.
Save bryanforbes/3828256 to your computer and use it in GitHub Desktop.
data-* bindings for Dojo
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