Backbone Basic Collection End Point Fetch
by iros
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<h1> Repos: </h1>
<div id="example_content"></div>
CSS
li {
padding: 10px;
border-bottom: 1px solid #eee;
}
li:hover {
background-color: #eaeaea
}
JavaScript
// A container for a repo object.
var Repo = Backbone.Model.extend({});
// A basic view rendering a single repo
var RepoView = Backbone.View.extend({
tagName: "li",
className: "repo",
render: function() {
// just render the repo name and description as the content of this element.
$(this.el).html(
'<b>' + this.model.get("name") + "</b> - " +
this.model.get("description"));
return this;
}
});
// A collection holding many repo objects.
// also responsible for performing the
// search that fetches them.
var Repos = Backbone.Collection.extend({
model: Repo,
initialize: function(models, options) {
this.language = options.language;
},
url: function() {
return "https://api.github.com/search/repositories?q=language:" +
this.language + "&sort=stars&order=desc";
},
parse: function(data) {
// note that the original result contains repos inside of an items array, not at
// the root of the response.
return data.items;
}
});
// A rendering of a collection of repos.
var ReposView = Backbone.View.extend({
tagName: "ul",
className: "repos",
render: function() {
// for each repo, create a view and prepend it to the list.
this.collection.each(function(repo) {
var repoView = new RepoView({
model: repo
});
$(this.el).prepend(repoView.render().el);
}, this);
return this;
}
});
// Create a new assembly language repo collection
var assemblyRepos = new Repos([], {
language: "assembly"
});
// create a view that will contain our repos
var assemblyReposView = new ReposView({
collection: assemblyRepos
});
// on a successful fetch, update the collection.
assemblyRepos.fetch({
success: function(collection) {
$('#example_content').html(assemblyReposView.render().el);
}
});