473,428 Members | 1,596 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,428 software developers and data experts.

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.createElement("input");
this.textbox.type = "text";
this.textbox.addEventListener("blur", this.doThings, false);
someElement.appendChild(this.textbox);
}

MyType.prototype.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 2208
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.createElement("input");
this.textbox.type = "text";
this.textbox.addEventListener("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.appendChild(this.textbox);

}

MyType.prototype.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.createElement('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.call(obj);
}

button.appendChild(
document.createTextNode('show name ' + this.name)
);
el.appendChild(button);
}

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

// Create a couple of objects
var x = new Foo('Fred', document.getElementById('div0'));
var y = new Foo('Nerk', document.getElementById('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.createElement('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.call(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
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"> <!--...
3
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
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
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
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...
1
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) ...
60
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....
2
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...
7
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.