Yesterday, I asked a question that was very helpful to me.
I have rewritten most of the code by following tutorials, YouTube videos, and seeking help on Stack Overflow. However, I am unsure of what I am doing wrong when trying to push the JSON data to the underscore template.
Essentially, my goal is to extract data from a JSON array, loop through it, and display it. While I've watched tutorials using .get to achieve this, they were not dealing with a JSON array. Any assistance would be greatly appreciated.
This is how my code looks: (I've indicated the line where I think things are going wrong)
<body>
<div class="News"></div>
<script type="text/template" id="NewsTemplate">
<table>
<% _.each(NewsCollection, function(item) { %>
<tr>
<td><%= item.title %></td>
</tr>
<% }); %>
</table>
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone.js"></script>
<script type="text/javascript">
var NewsModel = Backbone.Model.extend({ });
// Define backbone collection to retrieve Google News JSON array
var NewsCollection = Backbone.Collection.extend({
url: 'data.js'
})
var NewsList = Backbone.View.extend({
el: '.News',
template: _.template($("#NewsTemplate").html()),
render: function () {
var that = this;
var NewsItems = new NewsCollection();
NewsItems.fetch({
// I suspect something might be off here
success: function (NewsItems) {
$(this.el).html(that.template({'collection.toJSON': NewsItems.toJSON()}));
}
})
}
});
// Router for Backbone to take action upon loading homepage
var Router = Backbone.Router.extend({
routes: {
'': 'home'
}
});
var newslist = new NewsList();
var router = new Router();
router.on('route:home' , function (){
newslist.render();
});
Backbone.history.start();
</script>
</body>