473,406 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

'this', event handlers, and namespaces

Hi,

Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: function(e) {
this.doAlert();
}
}

document.addEventListener('keydown', Foo.doAlert, false);
This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached the
event handler to. I know I could just replace 'this' with "Foo.' but
my understanding is that I take a performance hit every time I make
such a global reference. And, since I'm developing a large web
application in Javascript, I'd like to avoid unnecessary performance
hits when possible.

Anyone know what is the accepted standard of what to do in this case?

Thanks!
Jeff
Jun 27 '08 #1
10 1398
On May 16, 9:27 am, Jeff Bigham <jeffrey.big...@gmail.comwrote:
Hi,

Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: function(e) {
this.doAlert();
}

}

document.addEventListener('keydown', Foo.doAlert, false);

This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached the
event handler to. I know I could just replace 'this' with "Foo.' but
my understanding is that I take a performance hit every time I make
such a global reference. And, since I'm developing a large web
application in Javascript, I'd like to avoid unnecessary performance
hits when possible.

Anyone know what is the accepted standard of what to do in this case?
Try this thread:

Subject: pseudo-namespacing in JavaScript
<URL:
http://groups.google.com.au/group/co...45e485506c4a92
>

--
Rob
Jun 27 '08 #2
jdd
On May 15, 7:27*pm, Jeff Bigham <jeffrey.big...@gmail.comwrote:
Hi,

Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
* doAlert: function() {
* * alert('hello');
* },
* myEventHandler: function(e) {
* * this.doAlert();
* }

}

document.addEventListener('keydown', Foo.doAlert, false);

This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached the
event handler to. *I know I could just replace 'this' with "Foo.' but
my understanding is that I take a performance hit every time I make
such a global reference. *And, since I'm developing a large web
application in Javascript, I'd like to avoid unnecessary performance
hits when possible.

Anyone know what is the accepted standard of what to do in this case?

Thanks!
Jeff
I don't know if it's the accepted standard of what to do, but you
could do something like:

var Foo = {
* doAlert: function() {
* * alert('hello');
* },
* myEventHandler: (function(t) {
that = t;
return function(e) {
* * that.doAlert();
};
})(this)
}

I don't think this would be avoiding a performance hit though, and you
probably shouldn't listen to my advice as I'm still a bit green on
javascript. Additionally, I think the proper solution depends on what
exactly you're trying to do.
Jun 27 '08 #3
Jeff Bigham wrote:
Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: function(e) {
this.doAlert();
}
}

document.addEventListener('keydown', Foo.doAlert, false);
Probably you meant to write

document.addEventListener('keydown', Foo.myEventHandler, false);

instead, as there is no `this' in Foo.doAlert().
This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached
the event handler to.
_added_ event _listener_ to

This is a FAQ, and the solution is simple:

document.addEventListener(
'keydown',
function(e) { Foo.myEventHandler(e) },
false);

That said, by convention only names of properties that refer to
constructors, and identifiers of constant primitive values, should begin
with a capital letter.
I know I could just replace 'this' with "Foo.' but my understanding
is that I take a performance hit every time I make such a global reference.
That is correct, as no identifier resolution is required for the `this'
value of the execution context. However, the evaluation loop would be very
short; the main issue here is maintainability: You really do not want to do
search and replace when you have to rename `Foo' (and you should do that).
And, since I'm developing a large web application in Javascript, I'd
like to avoid unnecessary performance hits when possible.
Good thinking, though.
Anyone know what is the accepted standard of what to do in this case?
There is no accepted standard about it, only common sense guided by the text
of the ECMAScript Specification and by the reality of its implementations.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #4
jdd wrote:
On May 15, 7:27 pm, Jeff Bigham <jeffrey.big...@gmail.comwrote:
>Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: function(e) {
this.doAlert();
}
}

document.addEventListener('keydown', Foo.doAlert, false);

This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached the
event handler to. [...]

Anyone know what is the accepted standard of what to do in this case?

I don't know if it's the accepted standard of what to do, but you
could do something like:

var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: (function(t) {
that = t;
return function(e) {
that.doAlert();
};
})(this)
}
This code does not address the problem at all. In the above scenario, the
`myEventHandler' property would be assigned a reference to a Function object
that calls the doAlert() method of the *Global Object* (or the object
referenced by the `that' property of an object in the scope chain, see
below) instead of the object referred to by `Foo'. A TypeError exception on
event is likely as the Global Object (or that object) is unlikely to have a
method of that name. It is semantically equal to

that = this;
var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: function(e) {
that.doAlert();
};
};

Also, the undeclared `that' identifier is inherently error-prone.

Please trim your quotes as recommended e.g. in the FAQ Notes.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jun 27 '08 #5
jdd
On May 15, 10:14*pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
This code does not address the problem at all. . . *
You are correct, thanks for the explanation.
Jun 27 '08 #6
On May 16, 1:27*am, Jeff Bigham <jeffrey.big...@gmail.comwrote:
Hi,

Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
* doAlert: function() {
* * alert('hello');
* },
* myEventHandler: function(e) {
* * this.doAlert();
* }

}

document.addEventListener('keydown', Foo.doAlert, false);

This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached the
event handler to. *I know I could just replace 'this' with "Foo.' but
my understanding is that I take a performance hit every time I make
such a global reference. *And, since I'm developing a large web
application in Javascript, I'd like to avoid unnecessary performance
hits when possible.

Anyone know what is the accepted standard of what to do in this case?

Thanks!
Jeff
<html lang="en"><head>
<title>untitled</title></head><body>
<script>
var c= ": No closure";
(function () {
var d, e, c= ": anon f closure !";;
var y= function (p) { return document.createElement(p) };
var z= function (p) {
document.body.appendChild(y('br'));
return document.body.appendChild(p);
};
var x= function (p) { (z(y('text'))).innerHTML= p };

var foo= function (e) {
var c= ": foo closure !";
var me= arguments.callee;
me.doAlert= function() { x(this.src+': onClick'+c) };
var doAlert= function() { x(this.src+': onMouseUp'+c) };

//function object method : foo.doAlert()
e.onclick= me.doAlert;
//foo local var:
e.onmouseup= doAlert;
//anonymous function:
e.onmouseover= function () { x(this.src+': onMouseOver'+c) };
return e;
};

foo.too= function () { x(this.src+': onMouseOut'+c) };

(e= foo(z(y('img')))).src="http://tinyurl.com/6nhepj"
//anonimous function object method 2:
e.onmouseout= foo.too;
(d=z(y('img'))).src="http://tinyurl.com/5ehxv5"
//anonimous function object method 2:
d.onmouseout= foo.too;
d.onmouseover= e.onmouseover;
})();
</script></body></html>
Jun 27 '08 #7
On May 16, 1:27*am, Jeff Bigham <jeffrey.big...@gmail.comwrote:
Hi,

Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
* doAlert: function() {
* * alert('hello');
* },
* myEventHandler: function(e) {
* * this.doAlert();
* }

}

document.addEventListener('keydown', Foo.doAlert, false);

This gives me an error because when responding to the event, the
object 'this' is the document because that's what I've attached the
event handler to. *I know I could just replace 'this' with "Foo.' but
my understanding is that I take a performance hit every time I make
such a global reference. *And, since I'm developing a large web
application in Javascript, I'd like to avoid unnecessary performance
hits when possible.

Anyone know what is the accepted standard of what to do in this case?

Thanks!
Jeff
<html lang="en"><head>
<title>untitled</title></head><body>
<script>
var c= ": No closure";
(function () {
var d, e, c= ": anon f closure !";;
var y= function (p) { return document.createElement(p) };
var z= function (p) { return document.body.appendChild(p) };
var x= function (p) {
z(y('br'));
(z(y('text'))).innerHTML= p;
};

var foo= function (e) {
var c= ": foo closure !";
var me= arguments.callee;
me.doAlert= function() { x(this.src+': onClick'+c) };
var doAlert= function() { x(this.src+': onMouseUp'+c) };

//function object method : foo.doAlert()
e.onclick= me.doAlert;
//foo local var:
e.onmouseup= doAlert;
//anonymous function:
e.onmouseover= function () { x(this.src+': onMouseOver'+c) };
return e;
};

foo.too= function () { x(this.src+': onMouseOut'+c) };

(e= foo(z(y('img')))).src="http://tinyurl.com/6nhepj"
//anonimous function object method 2:
e.onmouseout= foo.too;

(d=z(y('img'))).src="http://tinyurl.com/5ehxv5"
//anonimous function object method 2:
d.onmouseout= function () { x(this.src+': onMouseOut'+c) };
d.onmouseover= function () { x(this.src+': onMouseOver'+c) };
d.onclick= function() { x(this.src+': onClick'+c) };
d.onmouseup= function () { x(this.src+': onMouseUp'+c) };

(d=z(y('img'))).src="http://tinyurl.com/5j84u6"
//anonimous function object method 2:
d.onmouseout= e.onmouseout;
d.onmouseover= e.onmouseover;
d.onclick= e.onclick;
d.onmouseup= e.onmouseup;

})();
</script></body></html>
Jun 27 '08 #8
Jorge wrote:
On May 16, 1:27 am, Jeff Bigham <jeffrey.big...@gmail.comwrote:
>Anyone know what is the accepted standard of what to do in this case?
[...]

<html lang="en"><head>
<title>untitled</title></head><body>
<script>
var c= ": No closure";
(function () {
var d, e, c= ": anon f closure !";;
var y= function (p) { return document.createElement(p) };
var z= function (p) { return document.body.appendChild(p) };
var x= function (p) {
z(y('br'));
(z(y('text'))).innerHTML= p;
};

var foo= function (e) {
var c= ": foo closure !";
var me= arguments.callee;
me.doAlert= function() { x(this.src+': onClick'+c) };
var doAlert= function() { x(this.src+': onMouseUp'+c) };

//function object method : foo.doAlert()
e.onclick= me.doAlert;
[...]
Sorry, this does not come even close to an approach that could make it to
standard procedure, much less to the standards-compliant approach that the
OP was following already. It is not even Valid markup to begin with:

http://validator.w3.org/
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
Jun 27 '08 #9
Anyone know what is the accepted standard of what to do in this case?

There is no accepted standard about it, only common sense guided by the text
of the ECMAScript Specification and by the reality of its implementations.
Thanks. What you suggested worked well.

-Jeff
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #10
* Jeff Bigham wrote in comp.lang.javascript:
>Consider the following simplified code in which Foo is used as a
'namespace':

var Foo = {
doAlert: function() {
alert('hello');
},
myEventHandler: function(e) {
this.doAlert();
}
}

document.addEventListener('keydown', Foo.doAlert, false);
You would have to call the event handler method 'handleEvent' and pass
the object rather than the function to addEventListener, i.e., like so:

var Foo = {
doAlert: function() {
alert('hello');
},
handleEvent: function(e) {
this.doAlert();
}
}

document.addEventListener('keydown', Foo, false);

With your approach `this` should always be bound to e.currentTarget.
--
Björn Höhrmann · mailto:bj****@hoehrmann.de · http://bjoern.hoehrmann.de
Weinh. Str. 22 · Telefon: +49(0)621/4309674 · http://www.bjoernsworld.de
68309 Mannheim · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/
Jun 27 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: chandramohan.mani | last post by:
Does Event handlers work in netscape. If yes means can anyone please help me. <HTML><SCRIPT LANGUAGE="JScript"> function mouseclick() { alert("I was clicked on " +...
1
by: MuZZy | last post by:
Hi, Is there a way to remove all event handlers for a control's event? Say, i have a button and i want to remove all button.Click events for it - i don't know how many of them was hooked to the...
0
by: R Reyes | last post by:
Hi. I'm trying to make some event handlers for buttons that are nested within datalists, however I keep getting errors trying to access them and a blank page shows w/o any real error message. How...
5
by: Amit | last post by:
Hello! Is it possible to find how many event handlers an event has at runtime? How about finding whether or not an event has event handlers? In C# you can compare the event with null to check if...
1
by: hayrob | last post by:
If you have an event in VB.Net, how can you find out how many event handlers there are for the event? How can you find out what the event handlers are? How can you remove all event handlers?
5
by: zlf | last post by:
I have an UserControl created by other component, its creator attachs some event handlers to MouseDoubleClick event, but I do not like those events to be triggered while it is db-clicked. I want to...
1
by: Armin Zingler | last post by:
Hi, I add event handlers to different events of objects of different type. In an array or arraylist, I want to store the information about which events I added. Later, I want to process the...
3
by: =?Utf-8?B?ZWFndWlsYXI=?= | last post by:
Hi, I am trying to dynamically generate a menu, based on entries on a text or xml file. The text file contains the "tree" after which the menu will need to be created. Something like the...
0
by: \(O\)enone | last post by:
I'm working on some code which dynamically adds WinForms controls to a form. It's all working well but I'm having to manually call AddHandler repeatedly for each event I am using each time I add...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.