Created
December 13, 2011 00:33
-
-
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
This file contains 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
/* | |
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