Mapping Demos
The Mapping ($.js.map
) subset of the jsMetro framework provides a function to help map javscript objects to HTML elements. The ultimate goal is to make transforming assets from a server into HTML a simpler and more automatic process. It is not meant to be a general purpose data-object mapping tool.
Use
$.js.map(element, data, options)
element
- A jQuery element that represents how the object will be structured in HTML.data
- The data object containing the necessary data and relevant properties and structure.options
clone
- Set totrue
if you wish the returned object to be a clone of the supplied element. (Default:false
)
Basic Mapping
The following example maps a JSON object to the following HTML element structures (DOMs/OMs).
Title
Subtitle
HTML
<div id="Mapped" class="mapped-object"> <section data-key="meta"> <h3 data-key="title">Title</h3> <h4 data-key="subtitle">Subtitle</h4> </section> </div>
jQuery/Javascript
$('#BasicMappingButton').click(function(event) { event.preventDefault(); $.js.map( $('#Mapped'), { meta: { title: 'Hello, World', subtitle: 'The world as I see it.' } } ); });
Cloning
The mapper also has the builtin ability to build clones of HTML OMs and return the clones for use. This is particularly useful for adding elements to a page from an external source.
HTML
<div id="Mapped" class="mapped-object"> <section data-key="meta"> <h3 data-key="title">Title</h3> <h4 data-key="subtitle">Subtitle</h4> </section> </div> <div id="CloneBucket"></div>
jQuery/Javascript
Instead of just calling the function, we grab the returned value and append it to our bucket. Note the additional options
parameter that specifies that cloning should be active. Otherwise we will be returned the original element and a DOM move will occur.
$('#CloningButton').click(function(event) { event.preventDefault(); var clone = $.js.map( $('#Mapped'), { meta: { title: 'Cloned World', subtitle: 'World Created At: ' + (new Date()).format('MM/dd/yyyy HH:mm:ss') } }, { clone: true } ); $('#CloneBucket').append(clone); });