Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are the underscore methods in Backbone.js?

Educative Answers Team

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.

How to use them

  1. Define the Jquery, underscore, and backbone sources that are used to define backbone objects and underscore methods. Let’s take a look at the terminal below:
<script src= 

<script src= 
<script src= 
  1. For example, let’s define a classroom of students. In the terminal below, the Backbone Model is a single entity that defines one single 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

  1. Let’s define 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"
  1. Make a new Classroom and add these students to the Classroom using the .add method:
var classroom= new Classroom();
classroom.add([s1, s2, s3]);
  1. Initialize a 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 () {
  1. Define each of the underscore methods in the render function:
render: function () {
// _.each
// This method iterates through the entire list of students. 
_.each(this.collection.toJSON(),function(model){ console.log( + " , " + 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){
// _.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){
// _.pluck
// This method plucks all the "name" values from data provided and outputs them .     
var sd3 = _.pluck(this.collection.toJSON(),"name");
  1. Define this newclass class to implement the above terminology:
new newclass();


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring