I am an absolute beginner in Backbone.js and I presently have two challenges.
The first issue concerns the data output from a JSON feed. Some of the data from the JSON feed are not fetch and consequently not displayed. When I inspect the browser network traffic it confirms the browser has not retrieved the entire feed which leaves my app to output default information as defined in the Model.
The second issue is I don't know how to get the Backbone app to execute on pageload rather than when I enter code into the console area.
My code is below:
<script id='topicTemplate' type='text/template'>
<td> <%= author %> </td>
<td> <%= weight %> </td>
<td> <%= edit %> </td>
<td> <%= nid %> </td>
<td> <%= promoted %> </td>
<td> <%= status %> </td>
<td> <%= title %> </td>
<td> <%= content %> </td>
</script>
<!-- =============== -->
<!-- Javascript code -->
<!-- =============== -->
<script type="text/javascript">
// your JS code goes here
//Models
var TopicStruct = Backbone.Model.extend({
defaults: {
author: 'unassigned',
weight: '',
edit: '',
nid: '0',
promoted: 'n/a',
status: 'none-existent',
title: 'Test Topic',
content: 'none',
}
});
var Topic = Backbone.View.extend({
tagName: 'tr',
className: 'topic',
model: TopicStruct,
template: _.template( $('#topicTemplate').html() ),
initialize: function(){
this.render();
},
render: function(){
this.$el.html( this.template(this.model.toJSON()) );
}
});
//Collections
var Topics = Backbone.Collection.extend({
model: TopicStruct,
url: '/sites/backbone/coordinatorJSON.php',
render: function(){
console.log('Topics Render Responding!');
}
});
//views
var TopicsList = Backbone.View.extend({
model: 'Topic',
tagName: 'table',
className: 'topics',
initialize: function(){
console.log('TopicsList:View responding!');
this.render();
},
render: function(){
//console.log(this);
this.collection.each( function(topic){
eachtopic = new Topic({model:topic});
//console.log(eachtopic.el);
this.$el.append(eachtopic.el);
$('#data').append(this.$el);
}, this);
}
});
</script>
The JSON data take the following form:
[
{
"author": "22",
"weight": "8",
"edit": "<a href=\"/node/17/edit?destination=sort-coordinator-json\">edit</a>",
"nid": "17",
"promoted": "",
"status": "Active",
"title": "Social investment tax relief",
"Content": "<!--form-item-draggableviews--0-->"
},
{
"author": "23",
"weight": "0",
"edit": "<a href=\"/node/19/edit?destination=sort-coordinator-json\">edit</a>",
"nid": "19",
"promoted": "",
"status": "Approved",
"title": "National Insurance: £2,000 employment allowance",
"Content": "<!--form-item-draggableviews--1-->"
},
.
.
.
]
The image below shows my output: