I have a Foo class, with a method that generates HTML that is displayed. I want 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 called. Similarly, the onclick event has no way of knowing how to access this foo instance. Here is the 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 should show that onclick needs to call the correct instance of Foo.
I was thinking of passing a string to Foo that contains the variable name containing Foo, but this is similar to 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 are you offering?
I am also open to jQuery solutions.
source
share