4

我有一个类 Foo,它有一个生成显示 HTML 的方法。我希望 HTML 有一个onclick事件处理程序,它调用Foo.clickHandler. 问题是我不知道这个特定实例的Foo名称是什么。同样,onclick事件无法知道如何访问Foo. 这是一些代码:

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);
    }
}

非静态函数的要点是表明onclick需要调用正确的实例Foo

我曾考虑过将一个字符串传递给Foo包含包含的变量名Foo,但这似乎是反 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');

你有什么建议?

我也对 jQuery 解决方案持开放态度。

4

3 回答 3

1

我希望我能理解你的问题。我认为您遇到了是否使用单例的问题?

我个人会选择我要去的地方,例如:

单身人士:

<!-- 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/

于 2012-05-17T19:43:53.403 回答
1

在?之外是否可以访问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);​
于 2012-05-17T19:51:55.033 回答
0

嗯...我不是最好的 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替换容器。可能有更好的方法,但这就是我所得到的

于 2012-05-17T19:28:07.727 回答