javascript - Dynamically setting image in underscore template -


i'm using underscore templates render html list displays list of contacts.

the template looks this:

<li>  <span class="name">name: <=%data.name%></span>  <span class="email">name: <=%data.email%></span>  <img class="avatar" src="<=%data.avatar%>"></img> </li> 

the issue is, when set template data, source of image won't known. why? because data looks this:

contact = {   name: string, // i.e. 'john doe'   email: string, // i.e 'john@doe.com'   avatar: string // i.e. '11a93150-14d4-11e3' } 

the avatar not url, rather link remote database needs fetching. like:

function getavatar(uuid, cb) { // uuid 11a93150-14d4-11e3  window.db.getimageurl(function(url) {   cb(url); // url http://foo.com/avatar.png  }); } 

question is, there way write template instead of reading avatar value of contact object directly, can embed reference function getavatar when template rendered, fetches url image , sets avatar image url?

thanks in advance

here's example demonstrate how can call javascript functions , asynchornously update src attribute of thumbnails. i've tried simulate db call using settimeout , db using associative array.

html:

<script type='text/html' id='contacttemplate'>     <li id="contact-<%= avatar %>">       <span class = "name"> name: <%= name %> </span>      <span class="email">name: <%= email %></span>       <img class = "avatar" data-populate-path="<% getpath( avatar ) %>" />     </li> </script> <ul id='contactlist'></ul> 

javascript:

var contacts = [     {name: 'john doe', email: 'john@doe.com', avatar: '11a93150-14d4-11e3'},      {name: 'hannah smith', email: 'hannah@smith.com', avatar: '11a93150-14d4-1231' } ],  simulateddb = []; simulateddb['11a93150-14d4-11e3'] = "path avatar 1"; simulateddb['11a93150-14d4-1231'] = "path avatar 2";  $(document).ready(function () {     var compiled = _.template($("#contacttemplate ").html());      _.each(contacts, function (d, i) {         $("#contactlist").append(compiled(d));     }); }); function getpath(target) {     settimeout(updateavatar, 1000, target); } function updateavatar(target) {     $("#contact-"+target+" img").attr("src", simulateddb[target]); } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -