[Javascript] When object methods and event handlers collide

Roger Roelofs rer at datacompusa.com
Mon Jun 2 08:49:02 CDT 2003


subtitle: What is 'this'

I have the following javascript class defined, that doesn't work 
because in an event handler, 'this' no longer refers to the object the 
method belongs to.  Is there a way to get a reference to the object in 
this situation?  I've pasted in the code in case my question doesn't 
make sense.

----------
function DragControl(el){
	this.target = el;
	this.targetTop = 0;
	this.targetLeft = 0;
	this.startX = 0;
	this.startY = 0;

	this.target.onmousedown=this.start;
}

DragControl.prototype.start = function (e){
	if(!e) var e = window.event;
	if (!document.getElementById) return true;

	var tDebug = "";
	tDebug += showProps(this); // this seems to = e.srcElement
                        // not the object the method belongs to
	this.targetLeft = parseInt(this.target.style.left+0);
	this.targetTop = parseInt(this.target.style.top+0);
	this.startX = e.clientX;
	this.startY = e.clientY;
	this.target.onmousemove = this.move;
	this.target.onmouseup = this.stop;
	return false;
}

DragControl.prototype.move = function (e){
	if(!e) e = window.event;
	this.target.style.left = this.targetLeft + e.clientX - this.startX;
	this.target.style.top = this.targetTop + e.clientY - this.startY;
	return false;
}

DragControl.prototype.stop = function (e) {
	this.target.onmousemove = null;
	this.target.onmouseup = null;
}

on load I execute the following 2 lines of code to set up the 
association.

var mag = document.getElementById("mag");
magDragControl = new DragControl(mag);



More information about the Javascript mailing list