When assigning a click handler to a button and passing an object that contains a method to handle the click event the function context will not be assigned to the passed in method.
Here is a JS Fiddle that shows my understanding of how to overcome this:
http://jsfiddle.net/b53pk/
<!DOCTYPE html>
<html>
<body>
<button id="test">Click Me!</button>
<script>
function bind(context,name){
return function(){
return context[name].apply(context,arguments);
};
}
var button = {
clicked: false,
click: function(){
this.clicked = true;
console.log(this.clicked);
console.log(this);
}
};
var elem = document.getElementById("test");
elem.addEventListener("click",bind(button,"click"),false); //#2
</script>
</body>
</html>
However, if I'm just using regular objects then this problem doesn't occur.
I'm struggling to understand WHY these two behave differently:
http://jsfiddle.net/4FRg3/
var buttonElement = {
addHandler : function(fn){
fn();
}
}
var handler = {
clicked : false,
clickHandler : function(){
this.clicked = true;
console.log(this.clicked);
}
}
buttonElement.addHandler(handler.clickHandler);
Can someone help me understand what the difference is?