The correct way to call a javascript class method from an html event

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.

+3
source share
3 answers

Do nonStaticVariable clickHandler Foo? , - :

function Foo(){
    //changed these to private variables only accessible from within Foo
    var nonStaticVariable='Something non-static (different for every instance of Foo).';
    var clickHandler = function(){
        alert(nonStaticVariable);
    }
    this.getHTML=function(){
        return $('<a href="#">Click Me!</a>').click(clickHandler);
    }
}


var fooInstance = new Foo();

var button = fooInstance.getHTML();


$("#container").html(button);​
+1

, . , ?

, , :

Singleton:

<!-- HTML -->
<a href="javascript:Foo.clickHandler(this)">singleton click</a>

//Javascript

// blah blah Foo = ....
this.clickHandler = function(what)
{
   alert(what);
}

:

// blah blah setup Foo & perhaps prototype

var element = document.createElement("a"); // or getelementbyid etc
element.onClick = function()
{
   alert(this);
}

, .

, : http://www.selfcontained.us/2008/12/23/javascript-widget-approaches-singleton-vs-prototype/

+1

... OO, , ,

var fooHash = {name: "nameHere", type: "xxx", whatever: "whatever"};
var fooInstance = new Foo(fooHash); 

Foo -

function Foo(o){
    this.name = o.name;
    this.type = o.type; // etc....
}

this.name. , , ,

0

All Articles