2012-05-17 96 views
3

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

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的正确实例。

我曾经想过传递一个字符串,美孚,里面有包含富变量名,但是这似乎反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解决方案也很开放。

回答

1

nonStaticVariableclickHandler必须的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);​ 
0

嗯......我不是最好的面向对象的程序设计师,但你可以考绩哈希,它是一种相同的是你得到了什么

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替换容器。有可能是一种更好的方式,但这是我得到的全部

1

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

个人而言,我会选择在那里我用它去,例如:

辛格尔顿:

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

//Javascript 

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

OR

原型:

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

+0

我想我有一个想法。如果我使用jQuery创建一个元素,然后附加一个带有对我的eventHandler的引用的事件,并将这些元素添加到DOM,引用将被转换为字符串并添加到onclick属性中?或者它会保持一个引用,并在点击时调用正确的eventHandler? – Joel

+0

是的,jquery使这真的很容易,例如:$(“a.my-clickablestuff”)。click(function(){alert($(this)});会为你做这一切,你甚至不需要添加href =“javascript ...关于链接。 – Alex