The Lodash _.bindAll() method 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)
Parameter: This method accepts two parameters as mentioned above and described below:
- object: It is the object that contains different methods and functions to bind.
- methodNames: It is the names of methods present in the object.
Return value: It returns an object.
Note: This method doesn’t set the “length” property of bound functions.
Below example illustrate the Lodash _.bindAll() method in JavaScript:
Example 1:
Javascript
<!DOCTYPE html> <html> <head> <script src= </script></head> <body> <button id="button">button</button> <script type="text/javascript"> var object={ label : 'neveropen', click: function(){ console.log( 'clicked: ' + this.label); }, hover: function(){ console.log( 'hovering: ' + this.label); } }; // Using bindAll() method of lodash _.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:
Javascript
<!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+" neveropen") }, func: function(){ console.log( 'Function : ' + this.printNum); }, output: function(){ "Output : "+this.printNum(); } }; // Using bindAll() method of lodash _.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:
Reference: https://docs-lodash.com/v4/bind-all/

