Lodash _.bindAll() Method
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.
Javascript
<!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);
}
};
_.bindAll(object, 'click' , 'hover' );
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
Javascript
<!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();
}
};
_.bindAll(object, 'func' , 'output' );
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/
Last Updated :
13 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...