_.bindAll(object, *methodNames)
- object
- object
- *methodNames
- string
methodNamesで指定されたオブジェクトにいくつかのメソッドをバインドし、それらが呼び出されるたびにそのオブジェクトのコンテキストで実行されます。
イベントハンドラーとして使用される関数をバインドするのに非常に便利です。
イベントハンドラーは、そうでなければかなり役に立たないthisで呼び出されます。
methodNamesは必須です。
サンプル
Javascript
const buttonView = {
label : 'underscore',
onClick: function(){ alert('clicked: ' + this.label); },
onHover: function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
document.getElementById('code1-execute').addEventListener('click', (e) => {
// When the button is clicked, this.label will have the correct value.
buttonView.onClick();
});
HTML
<span class="btn btn-execute" id="code1-execute">実行</span>
<div id="code1-dump"></div>