473,602 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Events and "this" caveats

Is there any good reading about pitfalls of scoping when using events?

Here is my specific issue:

function MyType()
{
this.foo = "bar";
this.textbox = document.create Element("input" );
this.textbox.ty pe = "text";
this.textbox.ad dEventListener( "blur", this.doThings, false);
someElement.app endChild(this.t extbox);
}

MyType.prototyp e.doThings = function()
{
//Wanted "bar", but 'this' is not the MyType object.
//Rather, it's the element that triggered the event.
alert(this.foo) ;
}

I'm trying to have an event trigger a function call in an object
instance. Is this fundamentally impossible / undesirable in javascript?

Thanks,
Jeremy
May 31 '07 #1
5 2227
On May 31, 1:22 pm, Jeremy <jer...@pinacol .comwrote:
Is there any good reading about pitfalls of scoping when using events?
The fundamental thing to remember about a function's this keyword is
that it is set by the calling function when the function is called.
To find articles, search on "javascript this keyword" or in these
archives for "this keyword operator". Mike Winter wrote a couple of
great posts a while back.

Here are a few references - some are better than others, you should
get the idea:

Mike Winter 1 (last post):
<URL:
http://groups.google.com.au/group/co...e16b48661bf7e2
>
Mike Winter 2:
<URL:
http://groups.google.com.au/group/co...dfb987df455e19
>
Quirksmode:
<URL: http://www.quirksmode.org/js/this.html >

Here is my specific issue:

function MyType()
{
this.foo = "bar";
this.textbox = document.create Element("input" );
this.textbox.ty pe = "text";
this.textbox.ad dEventListener( "blur", this.doThings, false);
Your problem here is that when the event is called, the function's
this keyword is set to the DOM element, not to your object. You can
use call or apply to set the this keyword, or pass a reference to the
object as a parameter.

However you do it, you will probably have a closure involving a DOM
object, which will likey create a memory leak in IE. The following
article tells you how to deal with that;

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >
someElement.app endChild(this.t extbox);

}

MyType.prototyp e.doThings = function()
{
//Wanted "bar", but 'this' is not the MyType object.
//Rather, it's the element that triggered the event.
alert(this.foo) ;

}

I'm trying to have an event trigger a function call in an object
instance. Is this fundamentally impossible / undesirable in javascript?
Neither, as long as you are careful about memory usage - keep the
contstructor function small and neat and (for IE's sake) detach event
listeners onunload. Here is a very quick and dirty example, Richard
Cornford's article on closures will fill in the blanks:

<div id="div0"></div>

<script type="text/javascript">

function Foo (name, el) {
this.name = name;
this.button = document.create Element('button ');

// Create a local variable for convenience
var button = this.button;

// Get a reference to the new object to use later
var obj = this;

button.onclick = function(){

// Use call to set the value of 'this'
// *when the function is called*
obj.showName.ca ll(obj);
}

button.appendCh ild(
document.create TextNode('show name ' + this.name)
);
el.appendChild( button);
}

Foo.prototype.s howName = function(){
alert( this.name );
}

// Create a couple of objects
var x = new Foo('Fred', document.getEle mentById('div0' ));
var y = new Foo('Nerk', document.getEle mentById('div0' ));

</script>
--
Rob

May 31 '07 #2
RobG wrote:
On May 31, 1:22 pm, Jeremy <jer...@pinacol .comwrote:
>Is there any good reading about pitfalls of scoping when using events?

The fundamental thing to remember about a function's this keyword is
that it is set by the calling function when the function is called.
To find articles, search on "javascript this keyword" or in these
archives for "this keyword operator". Mike Winter wrote a couple of
great posts a while back.

Here are a few references - some are better than others, you should
get the idea:

<snip>
--
Rob
Rob,

That was probably the single most informative post I have ever seen on
c.l.javascript. Thanks!

Before I saw your post, I just adjusted my event handlers to deal with
the expected element instead, and then set a reference in that element's
DOM object to the object I wanted to access. Now, since I don't really
give a crap about IE (note how I'm using w3 event model and ignoring
IE's), I'm going to go back and change it to work the way I originally
wanted.

I only wish usenet wasn't so transient, because I'm sure that post would
be useful to countless people in the future (YOU try searching for
"this" on google groups and see if you get any useful results ;-))

Jeremy
May 31 '07 #3
On May 31, 6:52 pm, RobG <r...@iinet.net .auwrote:
[...]
function Foo (name, el) {
this.name = name;
this.button = document.create Element('button ');

// Create a local variable for convenience
var button = this.button;

// Get a reference to the new object to use later
var obj = this;

button.onclick = function(){

// Use call to set the value of 'this'
// *when the function is called*
obj.showName.ca ll(obj);
Of course call isn't needed here at all, showName is called as a
method of obj so its this keyword will be set to obj:

obj.showName();

will do.
--
Rob

May 31 '07 #4
On Jun 1, 3:16 am, Jeremy <jer...@pinacol .comwrote:
[...]
Now, since I don't really
give a crap about IE (note how I'm using w3 event model and ignoring
IE's)
If you are developing for the web, that view is difficult to support.
If you are developing for an intranet where something other than IE is
the standard browser, you can probably get away with it.
--
Rob

May 31 '07 #5
RobG wrote:
On Jun 1, 3:16 am, Jeremy <jer...@pinacol .comwrote:

If you are developing for the web, that view is difficult to support.
If you are developing for an intranet where something other than IE is
the standard browser, you can probably get away with it.
--
Rob
The second is true. Rather, this is an app mostly for use by
developers, and will never really be seen by any end-users. I'm making
the assumption that developers are well-informed enough not to use I.E.
for daily browsing. I could be wrong, of course, but it is not worth it
to me to code to IE for this particular app.

Jeremy
Jun 1 '07 #6

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

Similar topics

5
2773
by: Michael Stevens | last post by:
Probably the wrong wording but since I'm not a scripter I won't claim to know what I'm talking about. I got this script from www.htmlgoodies.com <script language="JavaScript"> <!-- window.open ('photos01.html','photogallery',config='height=550, width=750,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
3
1721
by: maadhuu | last post by:
well,i am curious to know what would be the output of the following: delete this; basically , comment on this .
32
3165
by: Christopher Benson-Manica | last post by:
Is the following code legal, moral, and advisable? #include <iostream> class A { private: int a; public: A() : a(42) {}
1
1983
by: tnhoe | last post by:
Hi, <Form method='post' action="next.htm?btn="+"this.myform.myobj.value"> What is the correct syntax for above ? Regards Hoe
4
1325
by: Richard | last post by:
When I reference "this" in call to event, I get the following error: An unhandled exception of type 'System.NullReferenceException' occurred in csbasesockets.dll Additional information: Object reference not set to an instance of an object. Here is a summary of my code:
1
1287
by: Shapper | last post by:
Hello, I am accessing a value in a XML value: news.Load(Server.MapPath("xml/ news.rss")) newslabel.Text = CType(news.SelectSingleNode("rss version=&quot;2.0 &quot;/channel/title").InnerText, String) The XML file: <?xml version="1.0"?>
60
5016
by: Dave | last post by:
I'm never quite sure whether to use "this." or not when referring to fields or properties in the same class. It obviously works just fine without it but sometimes I wonder if using this. consistently may make the code easier to understand for someone else, etc. Using "this." makes it immediately clear, for example, that the variable being referred to is a member of the same class and is not declared in the method as a local variable. ...
2
2001
by: danny.dion | last post by:
Hi ! I have a question about JScript : I have an object class wich dynamically creates a control in the page. Then it binds an event to that control, pointing on one of its methods (the object's). This method, in turn, calls other of its own methods... The binding seems ok and the change() method does get called. But I get an error message (This object does not support this property or method) when I call other methods on the...
7
1706
by: szimek | last post by:
Hi, I've got this very simple code: <body onclick="foo(event, this)"> Inside foo method in IE "this" is body object, but in FF it's window object - at least that's what MS Script Editor and Firebug are saying. Any ideas why it works like that?
0
7993
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
8401
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
8268
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
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
5867
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
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3900
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...
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.