Skip to content

Commit

Permalink
Add example 08. Reuse a template various times, and JSONP data load.
Browse files Browse the repository at this point in the history
  • Loading branch information
beebole committed Jul 6, 2009
1 parent 73fd8c8 commit afa65f8
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
11 changes: 11 additions & 0 deletions index.html
Expand Up @@ -136,6 +136,17 @@ <h3>Recursion</h3>
</ul>
</div>
</li>

<li class="ex08">
<h3>Reuse a template and load JSONP data</h3>
<div class="template">
<div id="clock">
It is now <span class="hour"></span> : <span class="minute"></span> : <span class="second"></span><br />
In <span class="tz"></span>
</div>
<p><a href="#" onclick="clearTimeout(_to);return false;">stop</a></p>
</div>
</li>
</ul>
</div>
</body>
Expand Down
53 changes: 52 additions & 1 deletion js/examples.js
Expand Up @@ -186,4 +186,55 @@ var ex07 = {
}
}
}
};
};

var ex08 = function(){
var
// Get the html source (cross lib using $p)
// adapt it to your library if you want. i.e: $( '#clock' ) for jQuery
html = $p( '#clock' ),

// json service returning the current time for a timezone
tz = 'Europe/Brussels',
url = 'http://json-time.appspot.com/time.json?tz='+tz+'&callback=showTime&cache=',

//directive to render the template
directive = {
'span.hour': overlay('hour'),
'span.minute': overlay('minute'),
'span.second': overlay('second'),
'span.tz': 'tz'
},

// compile the template once
template = html.compile( directive );

// utility fn to add leading 0 to numbers
function overlay(what){
return function(a){
var val = a.context[what];
return val === 0 ? '00' : val < 10 ? '0' + val : val;
};
}

// JSONP load - script injection with callback function (cross lib GET example)
var noCache = 0;
function loadTime(){
var old = document.getElementById('dataLoad'),
s = document.createElement("script");
s.src = url + noCache++;
!old ? document.body.appendChild(s) : document.body.replaceChild(s, old);
s.id = 'dataLoad';
}

// Render the template
window.showTime = function(data){
// rendering but reusing the compiled function template
html = html.render( data, template );
// redo it every sec
window._to = setTimeout( loadTime, 1000 );
};

// Call the time service
loadTime();
};
3 changes: 3 additions & 0 deletions js/index.js
Expand Up @@ -123,6 +123,9 @@ var loadLib, runAll, run;
// run a transformation
function transform(ex, debug){
var template;
if(typeof ex === 'function'){
return ex();
}

switch(currLib){
case 'domassistant':
Expand Down

0 comments on commit afa65f8

Please sign in to comment.