I'm using this pretty handy JavaScript template library: https://github.com/blueimp/JavaScript-Templates. I can create elements and add data to them as many are doing with underscore.js and mustache.js.
My problem comes when I want to add my own functions and not just strings to the object that will populate the template's various nodes. What i'd like to do is run the function nicetime() to update the time of my newly inserted <div>'s instead of just showing the time once.
Here's the code, and a full demo.
HTML:
<button data-id="1">1</button>
<div data-id="1"></div>
<div id="time_since"></div>
JS:
$(document.body).on('click', 'button', function(){
var id= $(this).data('id');
var data={id:id, string: "just now...", fxn: nicetime()};
var result = tmpl('<div id="string" data-id="'+id+'">{%=o.string%}</div>
<div id="function" data-id="'+id+'">{%=o.fxn%}</div>', data);
$('div[data-id="'+id+'"]').html(result);
nicetime();
});
function nicetime(){
var time = new Date();
var comment_date = setInterval(function() {
var time2 = time_since(time.getTime()/1000);
$('#time_since').html(time2);
return time2;
},
1000);
}
note: inside nicetime() there is a function time_since() which is available on the jsfiddle. It is for formatting the date like this: "1 second ago...".