Click to See Complete Forum and Search --> : Event handler/Dom problem, need help


hotwheelharry
June 7th, 2008, 10:46 PM
I have three different ways of registering events to some divs in IE, and I have three problems. The first div does not work at all, the second gets the event object but no instance variable, the third gets both but the event handler is defined in the HTML. I need the event handlers to be assigned in the script, like in the first 2 divs. I need the event handler to be able to receive the event object, and I need the handler to be able to get the instanceVar variable's members.

Basically, the reference of "this" in the handler does not refer to the instanceVar, but instead to the "window" in the first 2 divs. I need it to refer to the instanceVar. What am I doing wrong?



<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">

function objDef(){
this.importantVariable = 3;
}

var infoHolder;
objDef.prototype.instanceFunction = function(oEvent){
alert("important variable: " + this.importantVariable);

if(oEvent){
alert("\tEvent Information" +
"\n\nsrcElement: " + oEvent.srcElement +
"\n|-->srcElement.id: " + oEvent.srcElement.id +
"\ntype: " + oEvent.type)
}
else{
alert("oEvent: " + oEvent);
}

//possible solution, but too slow/inefficient
//possible, get: event.srcElement.id
//then do document.getElementById('id').name ... for the <div id="" name="jsObjName"></div>
//the name must be the same name as the object
//then do: eval(return(name)) gives... the original calling object (instanceVar)!!!
}


/* event object
srcElement The element that fired the event (target in firefox)
type Type of event
*/

var instanceVar = new objDef();

</script>
</head>
<body>
<form id="form1" runat="server">
<div id="div1" style="border: 2px solid black">
div1 Text
<br/><br/>
using: document.getElementById('div1').onclick = instanceVar.instanceFunction;
<br/><br/>
</div>

<div id="div2" style="border: 2px solid black">
div2 Text
<br/><br/>
using: document.getElementById('div2').attachEvent('onclick', instanceVar.instanceFunction);
<br/>
For Firefox:
<br/>
//document.getElementById('div2').addEventListener('onclick', instanseVar.instanceFunction, false);
<br/><br/>
</div>

<div id="div3" onclick="instanceVar.instanceFunction(event)" style="border: 2px solid black">
div3 Text
<br/><br/>
using: onclick="instanceVar.instanceFunction(event)"
<br/><br/>
</div>

<script type="text/javascript">

//set document event handler to the instance function,
//this refers to the calling HTML element
//(in this case: this referes to "div1")
document.getElementById('div1').onclick = instanceVar.instanceFunction;


//adds the instanceFunction as an event
//handler for the html element
//(this case: this refers to "window")
document.getElementById('div2').attachEvent('onclick', instanceVar.instanceFunction);


</script>


</form>
</body>
</html>