Skip to content

Creating DOM element attributes with Transparency

cybercussion edited this page Feb 8, 2013 · 3 revisions

How do I create attributes?

With directives.

Template:

<div class="template">
  <a class="my-item"></a>
  <p class="my-desc"></p>  
</div>

Javascript:

$(document).ready(function() {

  data = {
    link: "http://opensourcehacker.com",
    title: "Open Source Hacker",
    desc: "<b>Hacking</b> is just another <i>service</i> I offer"
    };

  directives = {
    'my-item': { 
          href: function() { return this.link; },
          text : function() { return this.title; }
     },
    'my-desc': {
          html: function() { return this.desc; }
     }
  };

  $(".template").render(data, directives);
});

Output:

<div class="template">
  <a class="my-item" href="http://opensourcehacker.com">Open Source Hacker</a>
  <p class="my-desc">
    <b>Hacking</b>is just another
    <i>service</i>I offer</p>
</div>

JSFiddle