DOM event listeners/handler with .bind()
by web5me
HTML
<button id="theButton">The Button</button>
<div id="theDiv">The Div</div>
<a id="theLink" href="javascript:;">The Link</a>
JavaScript
var button = document.getElementById('theButton');
var link = document.getElementById('theLink');
var div = document.getElementById('theDiv');
function alertThis() {
alert('this.id == "'+ this.id +'"');
}
// listener with default handler
button.addEventListener('click', alertThis);
// this.id -> 'theButton' (element.id)
// listener with handler bound to a simple object (bind returns a bound function)
div.addEventListener('click', alertThis.bind({id: 'simple object'}));
// this.id -> 'simple object'
// define a constructor
function Module() { this.id = 'Module instance' };
// instantiate an object from the constructor
module = new Module;
// overwrite alertThis with function bound to the new object
alertThis = alertThis.bind(module);
// Surprisingly this does not change the output when clicking the button! The button listener still uses the old alertThis!
// listener with handler bound to module object
link.addEventListener('click', alertThis);
// this.id -> 'Module instance'