I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specific thing I would like to add - updating my view whenever my model changes. I believe I need to implement some sort of listener for this purpose, but I have tried various approaches found on Stack Overflow without success.
Below is the code I have:
Item (The Backbone Model)
var Item = Backbone.Model.extend({
defaults: {
title: 'No Title Provided',
url_title: 'unique key for URL',
img_path: 'no image added',
comment: 'No comments provided',
category: 'No category specified',
rating: 0,
article: 'No article content available'
},
});
ItemCollection (The Backbone Collection)
var ItemCollection = Backbone.Collection.extend({
model: Item,
comparator: function(model) {
if (sortid == "rating") {
return -model.get(sortid); // sorts descending
} else {
return model.get(sortid); // sorts ascending
}
}
});
ItemShelfView (The Backbone View)
var ItemShelfView = Backbone.View.extend({
className: 'itemshelf',
tagName: 'div',
render: function() {
var self = this;
// iterate through each item in the collection
// and add it to the DOM
this.collection.each(function(item) {
var itemEl = $('<div />', {
class: "item well well-lg col-md-5"
});
var itemTitle = $('<h3 />').text(item.get('title')).attr('class', "col-md-12");
var itemLink = $('<a />').attr('href', '#detail/' + item.get('url_title')).attr('class', "btn btn-default navigate col-md-12").text('View full article');
var itemImage = $('<img />').attr('src', item.get('img_path')).attr('class', "thumbnail col-md-4");
var articleText = item.get('article');
var shortText = jQuery.trim(articleText).substring(0, 200).split(" ").slice(0, -1).join(" ") + "...";
var itemArticle = $('<p />').text(shortText).attr('class', "col-md-8");
var itemCategory = $('<span />').text(item.get('category')).attr('class', "col-md-8");
var itemRating = $('<b class="rating" />').text(item.get('rating')).attr('class', "col-md-8");
var itemComment = $('<span />').text(item.get('comment')).attr('class', "col-md-8");
itemEl.append(itemTitle);
itemEl.append(itemImage);
itemEl.append(itemArticle);
itemEl.append(itemLink);
itemEl.append(itemComment);
itemEl.append(itemCategory);
itemEl.append(itemRating);
self.$el.append(itemEl);
});
return this;
}
});
My AJAX call to retrieve JSON data
$.ajax({
url: 'api/items.json',
dataType: 'json',
success: function(data) {
console.log(data);
var items = new ItemCollection(data);
var shelf = new ItemShelfView({
collection: items
});
$('#app').append(shelf.render().$el);
window.items = items;
window.shelf = shelf; // make sure items can be edited
}
});
Thank you! (I have already extensively searched Stack Overflow for solutions.) Greetings!