2012-05-17 97 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