You need to bind the "this" variable to a different context, and assign the function object reference to the onclick.
Function.prototype.bind is included in the newer versions of the ECMAScript specification, so you'll need this snippet below to support older browsers:
if (!Function.prototype.bind) {
Function.prototype.bind = function(context) {
var self = this;
var fn = function() {
return self.apply(context, arguments);
};
fn.cleanup = function() {
self = fn = context = null;
};
return fn;
};
}
And to use it:
var myObject = {
doSomething: function(event) {
var button = event.target || event.srcElement;
// do something with button
// "this" points to myObject
alert(this === myObject); // alerts "true"
}
};
var element = document.getElementById("some_id");
element.onclick = myObject.doSomething.bind(myObject);
Perhaps a more traditional object oriented approach:
function Foo(element) {
this.element = element;
this.element.onclick = this.handleClick.bind(this);
}
Foo.prototype = {
element: null,
handleClick: function(event) {
var element = event.target || event.srcElement;
this.showButton(element);
},
showButton: function(button) {
alert(button.nodeName + "#" + button.id);
}
};
var foo = new Foo(document.getElementById("some_id"));