Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, and views with declarative event handling. It then connects it all to your existing API over a RESTful JSON interface.
Underscore is a JavaScript library that provides many functional programming helpers without extending any built-in objects.
You can learn a series of different underscore methods here. In this shot, we will see how .add
,
_.each
, _.find
, _.filter
, _.pluck
, etc. work.
<script src=
"https://code.jquery.com/jquery-3.1.0.min.js"></script>
<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.3.3/backbone-min.js"></script>
Student
. A **Backbone Collection is a collection of models. In the current example, Classroom
is a collection of the model Student
:var Student = Backbone.Model.extend();
var Classroom = Backbone.Collection.extend({
model: Student
});
name
and Roll
for a few students:var s1 = new Student({
name : "Alex Williams",
Roll : "110"
});
var s2= new Student({
name : "Jon Snow",
Roll : "122"
});
var s3= new Student({
name : "Mike Ross",
Roll : "180"
});
Classroom
and add these students to the Classroom
using the .add
method:var classroom= new Classroom();
classroom.add([s1, s2, s3]);
render
method in which we can define all the relevant underscore methods that can be used:var newclass= Backbone.View.extend({
collection: classroom,
initialize: function () {
this.render();
},
render
function:render: function () {
// _.each
// This method iterates through the entire list of students.
_.each(this.collection.toJSON(),function(model){ console.log(model.name + " , " + model.Roll);
})
// _.find
// This method finds the first obtained Roll number greater than 100 and outputs the name.
var sd1 = _.find(this.collection.toJSON(),function(model){
if(model.Roll > 100){
return model.name;
}
});
console.log(sd1);
// _.filter
// This method finds all the Roll numbers greater than 100 and outputs their names.
var sd2= _.filter(this.collection.toJSON(),function(model){
if(model.Roll > 100){
return model.name;
}
});
console.log(sd2)
// _.pluck
// This method plucks all the "name" values from data provided and outputs them .
var sd3 = _.pluck(this.collection.toJSON(),"name");
console.log(sd3);
}
});
newclass
class to implement the above terminology:new newclass();