Hi, I have a javascript object in which two DIV elements are created and kept private. I want to expose a function which allows the object users to bind a click event
handler to one DIV, but I can't make it work.
Here is my code:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test Page</title>
<script type="text/javascript">
function MyClass(){
this._oDiv1 = document.createElement("div");
this._oDiv1.style.cssText = "width:200px; height:150px; background-color:#0c0";
document.body.appendChild(this._oDiv1);
this._oDiv2 = document.createElement("div");
this._oDiv2.style.cssText = "width:150px; height:30px; background-color:#f55; color:black; margin-top:10px; text-align: center";
this._oDiv2.innerHTML = "Change to blue";
document.body.appendChild(this._oDiv2);
}
MyClass.prototype.addClick = function(){
this._oDiv2.onclick = function(){
this._oDiv1.style.backgroundColor = "#00c"; //problem happens here
return false;
};
//alert(this._oDiv2.onclick.toString());
};
function start(){
var o = new MyClass();
o.addClick();
}
</script>
</head>
<body onload="start();">
</body>
</html>
The function I exposed is "addClick" in which the click event handler is bound to this._oDiv2. The handler just does a simple work to change this._oDiv1's background
color, but this can not be done because the "this" inside the handler points to the element receiving the "click" (in this case it's "_oDiv2"). I have no idea how to
make "this" inside the handler pointing to the current instance of "MyClass" object. Can anyone help me please?
|