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.
Example 1: In this example, the code uses the Lodash library’s _.bindAll
method to ensure the correct context for functions when handling click and hover events on a button element in an HTML document.
<!DOCTYPE html> <html> <head> <script src=
</script>
</head> <body> <button id= "button" >button</button>
<script type= "text/javascript" >
let object={
label : 'GeeksforGeeks' ,
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: In this example, the code uses the Lodash library’s _.bindAll
method to bind functions to an object, and when a button is clicked in an HTML document
<!DOCTYPE html> <html> <head> <script src=
</script>
</head> <body> <button id= "button" >button</button>
<script type= "text/javascript" >
let 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() 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/