I have been using Backbone.js to act as a middleman between WordPress (using the super rad JSON API plugin) and my front end.
Each of my WordPress posts has a YouTube video ID attached to it, which is getting pulled back when I fetch the collection.
I am trying to work out the best point within the application to go out and parse the video ID to get the total video views.
This is code that is fetching the collection model:
parse: function(response) {
return response.posts;
}
And the following code is then rendering the appropriate view.
this.getCollection().each(function(model) {
var view = new App.Thumbnail.View({model: model});
var item = $(view.render().el);
this.container.append(item);
});
At some point in this process, I need the thumbnails to assign themselves the video count. This is the code I have for grabbing the YouTube view count:
function getYoutubeViewCount(videoID) {
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2&alt=json",
dataType: "jsonp",
success: function (data) { console.log(data.entry.yt$statistics.viewCount); }
});
}
So my question is, where do you think the best place to fetch the view count is? Should I create a sub-model that fetches the count? Or do it outside of backbone.js?
Any help would be beyond appreciated!
Thanks in advance,
Charlie.
The
viewCountshould be an attribute on your Video model subclass. You can load both the wordpress data for the video and the youtube count in parallel before instantiating your model, or you can instantiate your model with the data from wordpress while the youtube data is being fetched and latered applied. Once you get the view count from youtube,setit on the corresponding model instance. Have your view bind to thechange:viewCountevent on the model and re-render itself (or at least shove the view count into the appropriate element in the DOM) once this data is loaded.As to WHEN you do this, probably you should start fetching the view count(s) in the background as soon as you have your basic Video model instance created and populated with its basic attributes from your wordpress data source. Or you can choose to load view counts later lazily when the video is played or scrolled into the viewport or moused over or whatever.