underscore.js中的BindAll()函數用於綁定對象上的許多方法。每個方法都有一個方法名稱。使用事件處理程序很方便。
用法:
_.bindAll(object, *methodNames)
參數:
- Object:它是包含要綁定的不同方法和函數的對象。
- methodNames:它是對象中存在的方法的名稱。
返回值:它什麽也不返回。
注意:在通過代碼直接在瀏覽器中使用此代碼之前,請鏈接下劃線CDN。
範例1:
<!DOCTYPE html>
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</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>
輸出:
範例2:
<!DOCTYPE html>
<html>
<head>
<script src =
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</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>
輸出:
相關用法
- PHP each()用法及代碼示例
- p5.js nfc()用法及代碼示例
- p5.js nf()用法及代碼示例
- PHP Ds\Set contains()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- CSS url()用法及代碼示例
- p5.js box()用法及代碼示例
- p5.js value()用法及代碼示例
- PHP Ds\Map xor()用法及代碼示例
- PHP Ds\Map put()用法及代碼示例
- PHP ord()用法及代碼示例
- p5.js nfp()用法及代碼示例
- p5.js nfs()用法及代碼示例
- p5.js pan()用法及代碼示例
- PHP Ds\Set xor()用法及代碼示例
- PHP exp()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Underscore.js _.bindAll() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。