473,597 Members | 2,413 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using object methods in addEventListene r

When you use addEventListene r (or addEvent in IE) to call an object
method, does it call it with the correct this parameter?

The ECMAScript reference has a lot to say about the caller using
Function.protot ype.call or Function.protot ype.apply and passing the
correct this pointer for the context, but how does addEventListene r
determine the correct this pointer. Or does it just punt and pass the
global context, thus making it impossible to refer to the object this
in an object method used as an event listener?

I could not find any reference to this in the W3C DOM-2 documentation.

/Joe
Jul 20 '05 #1
6 17199
jo****@zircon.s eattle.wa.us (Joe Kelsey) writes:
When you use addEventListene r (or addEvent in IE) to call an object
method, does it call it with the correct this parameter?
Absolutely! Ofcourse, whether that "this" value is the one you expect,
that is another question :).

If you use
node.addEventLi stener("click", foo.method,fals e)
and then click on the node, the function referred to by "foo.method "
is executed with "this" referring to "node". Just as if you had
used
node.onclick=fo o.method;
It never refers to "foo", which some might consider the correct value
of "this".
(Tested in Opera 7 and Mozilla FB 0.6)

If you use the IE version:
node.attachEven t("onclick",foo .method)
then the function is executed with this referring to the global (window)
object.
(Tested in IE6)
The ECMAScript reference has a lot to say about the caller using
Function.protot ype.call or Function.protot ype.apply and passing the
correct this pointer for the context, but how does addEventListene r
determine the correct this pointer.
It takes the object the event handler is assigned to, just as if it
was made a property of that object.
Or does it just punt and pass the global context, thus making it
impossible to refer to the object this in an object method used as
an event listener?
IE does that.
I could not find any reference to this in the W3C DOM-2 documentation.


That would be in W3C DOM 2 Events, and it doesn't say that. The
specification of an eventListener is an interface (i.e., an object
description) that contains a function to be called. That is because
it is written for languages that doesn't have first class functions,
like Javascript does. In such a language, the "this" value would be
the wrapper object for the function.
In Javascript we just pass the function itself, so it doesn't have
an obvious base object. Smart people made addEventHandler works as
close to assigning directly to the "onclick" property, but it is
not a requirement. IE didn't.

The DOM 2 Event specification gives another way of accessing the
node that an eventListener is assigned to: the "currentTar get" property
of the event. That won't help you for IE, ofcourse.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
Lasse Reichstein Nielsen <lr*@hotpop.com > wrote in message news:<d6******* ***@hotpop.com> ...
jo****@zircon.s eattle.wa.us (Joe Kelsey) writes:
When you use addEventListene r (or addEvent in IE) to call an object
method, does it call it with the correct this parameter?


Absolutely! Ofcourse, whether that "this" value is the one you expect,
that is another question :).

If you use
node.addEventLi stener("click", foo.method,fals e)
and then click on the node, the function referred to by "foo.method "
is executed with "this" referring to "node". Just as if you had
used
node.onclick=fo o.method;
It never refers to "foo", which some might consider the correct value
of "this".
(Tested in Opera 7 and Mozilla FB 0.6)

If you use the IE version:
node.attachEven t("onclick",foo .method)
then the function is executed with this referring to the global (window)
object.
(Tested in IE6)


So attachEvent in IE does something completely different from
specifying code directly in onclick="" in HTML? I mean I can put this
directly into the onclick HTML spec

<input blah...blah...
onclick="update Something (param1, 'param2', this.value);">

and expect that this.value refers to the input node. But if I
construct the Function inside javascript

var firstPart = "updateSomethin g (param1, ";
var lastPart = ", this.value);";
addEvent (node, "change", new Function (firstPart + "'param2'" +
lastPart), false);

Where node is a previously created element (e.g.,
document.create Element) and addEvent is a suitably defined function to
take care of the difference between addEventListene r and attachEvent,
then this.value will not work in IE?

If IE really supplies the global window context as this to the event
function, then it seems impossible to emulate the HTML behavior from
javascript.

I want to move some bizarre use of <script> as template html into
javascript. That means creating dynamic elements that include
onchange handlers. All of the handlers basically look the same except
for the 'param2' value.

/Joe
Jul 20 '05 #3
"Joe Kelsey" <jo****@zircon. seattle.wa.us> wrote in message
news:15******** *************** ***@posting.goo gle.com...
<snip>
var firstPart = "updateSomethin g (param1, ";
var lastPart = ", this.value);";
addEvent (node, "change", new Function (firstPart +
"'param2'" + lastPart), false);

<snip>

node.onchange = new Function(firstP art +"'param2'" + lastPart);

Works consistently in current browsers.

If you insist on playing with addEventListene r and attachEvent then
closure based solutions can be applied to rectify IE's deficiencies (and
maybe include param2 in the closure and avoid the need to explicitly
call the Function constructor to create a new function for each event
handler).

Richard.
Jul 20 '05 #4
"Richard Cornford" <ri*****@litote s.demon.co.uk> wrote in message news:<bi******* ***@hercules.bt internet.com>.. .
node.onchange = new Function(firstP art +"'param2'" + lastPart);

Works consistently in current browsers.


Does a standard exist which specifies this behavior or do the browsers
"just do it"? As far as I can tell from reading the DOM documents, no
"onchange" attribute exists in the various Element or Node
descriptions. Have I missed something?

Also, why prefer a closure using a function expression to creating a
new Function object? Does creating a new Function object involve some
sort of penalty that function expressions do not have? Do you just
prefer closures? Something to do with parse-time versus run-time?

/Joe
Jul 20 '05 #5
On 27 Aug 2003 15:45:20 -0700, jo****@zircon.s eattle.wa.us (Joe
Kelsey) wrote:
"Richard Cornford" <ri*****@litote s.demon.co.uk> wrote in message news:<bi******* ***@hercules.bt internet.com>.. .
node.onchange = new Function(firstP art +"'param2'" + lastPart);

Works consistently in current browsers.
Does a standard exist which specifies this behavior or do the browsers
"just do it"?


It's HTML DOM 0 as it's known...
As far as I can tell from reading the DOM documents, no
"onchange" attribute exists in the various Element or Node
descriptions .
No, AddEventListene r etc. is the appropriate method, but DOM Level 0
is more sensible now (you use "document" right, that's not in a
standard either just DOM 0)
Also, why prefer a closure using a function expression to creating a
new Function object? Does creating a new Function object involve some
sort of penalty that function expressions do not have?


It's very expensive, it's just like eval...

Jim.
--
comp.lang.javas cript FAQ - http://jibbering.com/faq/

Jul 20 '05 #6
"Joe Kelsey" <jo****@zircon. seattle.wa.us> wrote in message
news:15******** *************** ***@posting.goo gle.com...
"Richard Cornford" <ri*****@litote s.demon.co.uk> wrote in message news:<bi******* ***@hercules.bt internet.com>.. .
node.onchange = new Function(firstP art +"'param2'" + lastPart);

Works consistently in current browsers.


Does a standard exist which specifies this behavior or do
the browsers "just do it"?


They just do it, and have been doing it for so long that no browser
manufacturer would dare drop the feature for fear of producing a browser
that looked like it did not work with much of the web.

The number of events supported on different elements in the DOM varies,
with IE supporting the greatest number of events through defined
properties of the elements and Netscape 4 supporting just a limited
number of events (and having fewest accessible elements anyway). Though
Netscape 4 support is not relevant as it has already failed at
document.create Element (or before).
As far as I can tell from reading the DOM documents, no
"onchange" attribute exists in the various Element or Node
descriptions . Have I missed something?
I used the onchange property because you were passing the string
"change" as the second parameter to your - addEvent - function, so I
assumed that you were interested in setting onchange handlers and would
not be attempting to use them on elements that do not support onchange
attributes. I haven't attempted to confirm this but I would suspect
that, for any Element type, the range of event handlers that can be set
as properties of the element corresponds exactly with the range of
events that can trigger functions when addEventListene r or attachEvent
are used.
Also, why prefer a closure using a function expression to
creating a new Function object?
Does creating a new Function object involve some
sort of penalty that function expressions do not have?
Why not? They both will fail under their own individual and very limited
set of circumstances. For that reason the Function constructor might be
preferred as its failure can be ascertained by testing before it
happens, allowing more controlled fall-back. While when inner functions
fail it is because the JavaScript version is so old that they are not
supported, becoming syntax errors and killing off script execution for
the entire page, but we are talking JavaScript version 1.0 (and maybe
1.1), so not something that needs to be worried about these days.

Closures are not without there drawbacks, they are among the easiest
ways of creating the circular JavaScript object <-> DOM element
references that induce the memory leak problem in IE. But can usually be
coded to avoid that problem, and if not additional code can be used as a
solution to that problem.

In this case I mentioned closures because they would offer the option of
addressing two conditions at once, the scope resolution of the function
in IE and the problem of passing a different - param2 - to each
function.

The Function constructor carries the penalty that its function body is
parsed on each invocation of the constructor. Authors used to IE will
often be expecting excellent performance from the eval function and the
Function constructor. Unfortunately both experience a wide range of
performances in different implementations , with some implementations
being up to 6 times slower than IE under most circumstances and, with
some code structures, up to 400 times slower (but that is very much the
exception).

Ironically one place where the Function constructor offers manifest
benefits is performance critical code that requires the repeated
execution of the same function (such as sorting a very big array of
objects using a custom comparison function) where the function body will
have to use parameters/identifiers/indexes unknown until the execution
of the script. A closure could do it but the Function constructor could
create a function hard-coded to the task and as a result as efficient as
it could be.
Do you just prefer closures?
I like closures. They allow very interesting possibilities (to say the
least).
Something to do with parse-time versus run-time?


That could be a factor.

In the end each has its place, I just think that the scope for the
appropriate application of the Function constructor is much more limited
than for the appropriate application of closures.

Richard.
Jul 20 '05 #7

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

Similar topics

11
1688
by: Oleg Alistratov | last post by:
Is in javascript a method to get object's identifier as string? E.g., may I write function GetName thus, that var v; var s = GetName(v); has led to s == "v"
8
4445
by: David McDivitt | last post by:
We have a massive java application to be made ADA compliant. We want onfocus and onblur events for each text field. The best way seems to be javascript, by cycling through all the nodes recursively after page load, and attaching the events. We already cycle through everything to set tabs. If nodename is LABEL, we should be able to use the FOR attribute, get the object referenced, and attach events on that object. When cycling through...
4
2313
by: Liming | last post by:
Hello all, I have a custom class object with some prototype methods like setKeyDownEvent, etc. The problem is on my webpage, after I instantiate the class, I try to do .addEventLister() to a textarea by attaching my custom class object's setKeyDownEvent,etc to it. Long story short, here is an example of my code.
7
2523
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written several methods that are working fine. The problem is if I want to dynamically assign an event handler to the object, the event handler is not called. What am I doing wrong? Below is a sample HTML doc with everything in place. <!DOCTYPE HTML PUBLIC...
3
3111
by: Greg A | last post by:
What I am unsuccessful at doing is adding the event listener to an object in memory which isn't referencing an HTML element: // DATA OBJECT CONSTRUCTOR function dataObject(id){ // EVENT this.addEventListener("error",function(event){this.err(event)},true); // METHOD
4
1685
by: yumbelie | last post by:
Hi, I've got an issue where I've created a prototype that contains 2 methods, and a few private variables. The first method simply registers the second method to be an event handler for the mousedown event. This prototype is instanced for each instance of a server control. Basically it's an asp panel and for each one on the aspx webpage, an instance of my JavaScript prototype is created. Okay, so, when the prototype is instanced ( var...
1
1370
by: vunet | last post by:
If I initializer my object as var obj = new SomeObject(); then I have some method inside of the object as: function SomeObject(){ ....... this.showLink = function(){ return "<a href='javascript:void(0)' onClick='obj.showMessage()'></
8
3727
Jezternz
by: Jezternz | last post by:
Ok, I am new to JS OOP, so bare with me. The code is quite large so I will summaries and simplify, to show the piece that isn't working. Ok I have defined a class and then an object with several methods.I call these: theclass, theclass.method1 and theclass.method2. Now what I want to do is from inside method1, I want to register an event handler for say "window" to run method2 on the current object. Heres some code, and if I haven't...
1
3801
by: JWest46088 | last post by:
I'm getting this error when I try to preview my code: TypeError: Error #1009: Cannot access a property or method of a null object reference. at therun4life_fla::MainTimeline/frame1() I don't know what it could be. I looked over my code several times, and I can't find anything. Maybe it isn't sticking out because I put the code in. All of this code is in the first frame. Any idea what it could be? stop(); about_mc.buttonMode =...
0
7959
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7883
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8263
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
6677
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5842
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3876
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3917
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2393
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1492
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.