I am having issues retrieving json data from a REST endpoint using Backbone. It will console.log the entire json source, but gives me an "Uncaught TypeError: Cannot read property 'length' of undefined" error for actual values within the JSON output. I am able to retrieve data as desired using a straight AJAX call to my REST endpoint as follows:
$.ajax({
async: false,
url: "http://myajaxcall.com/articles/featured",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
$.each(data.aside, function (index, value) {
console.log(value.headLine);
});
}
});
But I am unable to get BackBone to fetch the same data. Where in my fetch am I going wrong?
var featuredArticle = Backbone.Model.extend({
defaults: {
id: '',
headLine: '',
snippet: '',
fullStory: '',
location: '',
nsfw: '',
category: '',
relatedArticleIds: '',
hasVideoPlaceholder: '',
numberOfImages: ''
}
});
var featuredArticles = Backbone.Collection.extend({
model: featuredArticle,
url: 'http://myajaxcall.com/articles/featured'
});
var articleView = Backbone.View.extend({
tagName: 'ul',
render: function () {
var that = this;
var getfeaturedArticles = new featuredArticles();
getfeaturedArticles.fetch({
dataType:"json",
success: function(data) {
console.log(getfeaturedArticles);
$.each(data.aside, function (index, value) {
console.log(value.headline);
$(that.el).append('<li>' + value.headLine + '</li>');
});
}
})
return this;
}
});
var articles = new articleView();
$("body").append(articles.render().el);
The callback should be like this:
success: function(model, response) {
console.log(response);
}