I have a class Foo, with a method that generates HTML that is displayed. I want the HTML to have an onclick event handler that calls Foo.clickHandler. The problem is that I don't know what this particular instance of Foo is named. Likewise, the onclick event has no way of knowing how to access this instance of Foo. Here is some code:
function Foo(){
this.nonStaticVariable='Something non-static (different for every instance of Foo).';
this.getHTML=function(){
return '<a href="javascript:void(0);" onclick="/* How do I call Foo.clickHandler? */">Click Me!</a>';
}
this.clickHandler=function(){
alert(nonStaticVariable);
}
}
The point of the non-static function is to show that the onclick needs to call the correct instance of Foo.
I have thought about passing a string to Foo that contains the variable name that contains Foo, but this seems anti-OOP:
function Foo(container){
this.container=container;
this.nonStaticVariable='Something non-static (different for every instance of Foo).';
this.getHTML=function(){
return '<a href="javascript:void(0);" onclick="'+container+'.clickHandler();">Click Me!</a>';
}
this.clickHandler=function(){
alert(nonStaticVariable);
}
}
var fooInstance=new Foo('fooInstance');
What do you suggest?
I am open to jQuery solutions as well.