Apps
Apps

Reputation: 3389

Dojo creating DOM nodes dynamically

I'm trying to create a custom Dojo widget for my application.

<!-- Dojo widget Template  -->
<div class="newsHomeWidget">
    <table width="100%" cellspacing="0" cellpadding="0">
        <tbody dojoAttachPoint="newsHomeTableTbody">
            <!-- May be we need to repeat this code dynamically -->
            <tr>
                <td class="ncmseparate">
                    <a class="wordwrap" dojoAttachPoint="newsHomeLink"></a>
                </td>
            </tr>
        </tbody>
    </table>
</div>

This widget is to display the list of News that I get from my service.I will get the Data in JSON format. I need to display the News Text in the anchor tag whose class is wordWrap and the link to the news as the href of this anchor tag.

Since there can be multiple news, I need to repeat for each News. I would like to do this in the best way. I can manually create the DOM for each value of News using dojo.create or dojo.place.But that requires lot of hard coding. Could you please suggest me the best way to do this? Is it possible to do that in the Widget template itself?

Upvotes: 3

Views: 2215

Answers (1)

BuffaloBuffalo
BuffaloBuffalo

Reputation: 7852

The simplest way would be to create a private templated widget that represents an individual news item.

for example

dojo.declare('NewsItem',[dijit._Widget,dijit._Templated],{
  url:'',
  headline:'',
  //template abbreviated
  templateString:'<tr><td><a href="${url}>${headline}</a></td></tr>'
});

Then when you retrieve the list of news from your data service, you can just iterate over each element of that array and create a new NewsItem widget and place it in the your tbody, this.newsHomeTableTbody.

var newsArray = [...]
dojo.forEach(newsArray, function(newsLink){
  var newsItem = new NewsItem({
    url: newsLink.url,
    headline: newsLink.headline
  });
  newsItem.placeAt(this.newsHomeTableTbody);

},this);

Upvotes: 3

Related Questions