Last Updated : 13 Nov, 2023
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:
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=
"https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js">
</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=
"https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js">
</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/
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4