Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Underscore.js _.bindAll() Function

  • Last Updated : 24 Nov, 2021

BindAll() function in underscore.js is used to bind the number of methods on the object. Each method is given a method name. It is handy to work with the event handlers.

Syntax: 

_.bindAll(object, *methodNames)

Parameters:

  • Object: It is the object that contains different methods and functions to be bind.
  • methodNames: It is the names of methods present in the the object.

Return Value: It returns nothing.

Note: Please Link the underscore CDN before using this code directly in the browser through the code.

Example 1:




<!DOCTYPE html> 
<html> 
  <head> 
    <script src =  
    </script> 
  </head> 
  <body> 
    <button id="button">button</button>
    <script type="text/javascript"
      var object={
          label  : 'GeeksforGeeks',
          click: function(){ console.log(
                'clicked: ' + this.label); },
          hover: function(){ console.log(
               'hovering: ' + this.label); }
        };
        //using bindall function of underscorejs
        _.bindAll(object, 'click', 'hover');
        /* When the button is clicked, 
           this.label will have the correct value.*/
        let btn=document.querySelector("#button");
        btn.addEventListener('click', object.click);
        btn.addEventListener('click', object.hover);
    </script> 
  </body> 
</html>

Output:

Example 2:




<!DOCTYPE html> 
<html> 
  <head> 
    <script src =  
    </script> 
  </head> 
  <body> 
    <button id="button">button</button>
    <script type="text/javascript"
      var object={
          printNum:()=>{
            for(let i=0; i<5; i++)
                console.log(i+" geeksforgeeks")
          },
          func: function(){ console.log(
              'Function : ' + this.printNum); },
          output: function(){ "Output : "+this.printNum(); }
        };
        //using bindall function of underscorejs
        _.bindAll(object, 'func', 'output');
        // When the button is clicked 
        let btn=document.querySelector("#button");
        btn.addEventListener('click', object.func);
        btn.addEventListener('click', object.output);
    </script> 
  </body> 
</html>

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!