Skip to content

Instantly share code, notes, and snippets.

@methodin
Created December 13, 2011 00:33
Show Gist options
  • Save methodin/1469826 to your computer and use it in GitHub Desktop.
Save methodin/1469826 to your computer and use it in GitHub Desktop.
The simplest jQuery plugin I ever wrote - map a JSON object to a container of DOM elements
/*
HTML:
<div id="someParent">
<div id="title"></div>
<img id="img"/>
</div>
Data:
var r = {title:'This is a title', img:'http://someimage.jpg'}
Javascript:
$('#someParent').dataMap(r, {
img: function($obj, val) { $obj.attr('src', val); }
});
*/
(function( $ ) {
$.fn.dataMap = function(r, custom) {
for(var key in r) {
var children = this.find('#'+key+', .'+key);
// If the object is an array we have to handle that explicitly
if(Object.prototype.toString.apply(r[key]) === '[object Array]') {
// See if we've already cached the list child HTML (like <li>)
if(!children.data('cache')) {
var d = $('<div/>').append(children.find(":first").clone());
children.data('cache', d.html());
}
// Clear the current list and append the items to it using the cached HTML
var data = children.data('cache');
children.html('');
for(var i=0;i<r[key].length;i++) {
$(data).html(r[key][i]).appendTo(children);
}
} else {
// See if the user has any custom setters
if(custom && typeof custom[key] != 'undefined') custom[key](children, r[key]);
else {
if(children.is('img')) children.attr('src', r[key]);
else if(children.is('input,select,textarea')) children.val(r[key]);
else children.html(r[key]);
}
}
}
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment