//binding click functions
document.getElementById("btn-author").onclick = function() {
filterAuthor('Dan Brown');
};
document.getElementById("btn-subject").onclick = function() {
filterSubject('Comedy');
};
//app object
var App = {
Models: {},
Collections: {}
};
//model
App.Models.Book = Backbone.Model.extend({
title: "title",
author: "author",
subject: "subject",
printDetails: function() {
return "<b>title: </b>" + this.get('title') + ", <b>author: </b>" + this.get('author') + ", <b>subject: </b>" + this.get("subject");
}
});
//collection
App.Collections.Library = Backbone.Collection.extend({
model: App.Models.Book,
url: "/connectors",
filterByAuthor: function(author) { //filtering the models of a collection based on a condition
//map using usual JS mapping method
return this.filter(function(d) {
return d.get('author') === author;
});
},
filterBySubject: function(subject) {
//map using ECMAscript 6 arrow functions
return this.filter(d => d.get('subject') === subject);
}
});
//initialize books
var book1 = new App.Models.Book({
title: "Digital Fortress",
author: "Dan Brown",
subject: "Thriller"
});
var book2 = new App.Models.Book({
title: "The Lost Symbol",
author: "Dan Brown",
subject: "Comedy"
});
var book3 = new App.Models.Book({
title: "Love from both sides",
author: "Nick Spalding",
subject: "Romance"
});
var book4 = new App.Models.Book({
title: "Oh my venus",
author: "Shin Min Ah",
subject: "Comedy"
});
//initializ collection - library
var library = new App.Collections.Library([book1, book2, book3, book4]);
function filterAuthor(author) {
var set = library.filterByAuthor(author); //array of books
var toPrint = "";
set.map(function(book) { //iterate through the array of books
toPrint += book.printDetails() + "<br>"; //generate html string
});
document.getElementById("filter-by-author").innerHTML = toPrint;
}
function filterSubject(subject) {
var set = library.filterBySubject(subject); //array of books
var toPrint = "";
set.map(function(book) { //iterate through the array of books
toPrint += book.printDetails() + "<br>"; //generate html string
});
document.getElementById("filter-by-subject").innerHTML = toPrint;
}
<div class="box">
<button id="btn-author">Filter by author (Dan Brown)</button>
<div class='result' id="filter-by-author"></div>
</div>
<div class="box">
<button id="btn-subject">Filter by subject (Comedy)</button>
<div class='result' id="filter-by-subject"></div>
</div>
.box {
height: auto;
border: 1px solid black;
border-radius: 10px;
padding: 10px;
margin: 30px;
}
.result {
border: 1px solid #c9c9c9;
border-radius: 10px;
height: 200px;
padding: 5px;
margin: 10px;
}
External resources loaded into this fiddle: