473,801 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Events and the window keyword

Is it bad form to use the global window variable to reference an event
handlers window?

Like so:

function SortableTable() {

oFilterAdd = this.document.c reateElement("b utton");
oFilterAdd.setA ttribute("type" , "button");
oFilterAddText = this.document.c reateTextNode(" Add");
oFilterRemoveTe xt = this.document.c reateTextNode(" Remove");
document.append Child(oFilterAd d);
oFilterAdd.addE ventListener("c lick", this.addOnclick , false);
}

SortableTable.p rototype.addOnc lick = function () {

this.removeChil d(window.oFilte rAddText);
this.appendChil d(window.oFilte rRemoveText);
}

I realize i could pass the addOnClick function by reference such as:

oFilterAdd.addE ventListener("c lick", this.addOnclick (), false);

to avoid using the window variable. In that case, 'this' would refer to
the window object not the add buttons click method. However, I would
like to pass addOnClick by value as given in the first example.

Thanks,
Derek Basch

Jul 23 '05 #1
3 2414
Derek Basch wrote:

[Subject:] Events and the window keyword

Just so you know, there is no window keyword. It is just a
(well-known) global variable that refers back to the global object.
Is it bad form to use the global window variable to reference an event
handlers window?
Not really, though you might say that it's nicer to write something like

var global = this;

in global scope. You can now refer to the global object without
relying on DOM 0 behaviour. More to the point though, I see no reason
for you to refer to the global object directly, anyway.

[snip]
oFilterAdd = this.document.c reateElement("b utton");
The this operator seems unnecessary here, and elsewhere, in this
function (unless you have a document member, of course).
oFilterAdd.setA ttribute("type" , "button");
Unless you're using XHTML (true XHTML, not XHTML served as HTML), it's
preferable to use the shortcut properties:

oFilterAdd.type = 'button';

[snip]
this.removeChil d(window.oFilte rAddText);
this.appendChil d(window.oFilte rRemoveText);
Why do you feel the need to use the window global? Simply
oFilterAddText or oFilterRemoveTe xt will be sufficient (unless you
have variables with those names higher in the scope chain, which I
doubt is true).
I realize i could pass the addOnClick function by reference such as:

oFilterAdd.addE ventListener("c lick", this.addOnclick (), false);


That would be a function call, not a reference. In any case, it
wouldn't matter: addOnclick would be called as a member of oFilterAdd.

[snip]

A completely different approach would be to use a closure, avoiding
globals altogether (which is arguably better):

function SortableTable() {
var filter = document.create Element('button '),
addText = document.create TextNode('Add') ,
removeText = document.create TextNode('Remov e');

function listener(e) {
this.removeChil d(addText);
this.appendChil d(removeText);
}

filter.type = 'button';
document.append Child(filter);
filter.addEvent Listener('click ', listener, false);
}

However, something feels very odd about this whole question so I
assume you've omitted a lot of details.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
Michael Winter wrote:
Derek Basch wrote:
oFilterAdd = this.document.c reateElement("b utton");
The this operator seems unnecessary here, and elsewhere, in this
function (unless you have a document member, of course).


Yes, there was a document member. I have removed it though because it
was redundant.
this.removeChil d(window.oFilte rAddText);
this.appendChil d(window.oFilte rRemoveText);


Why do you feel the need to use the window global? Simply
oFilterAddText or oFilterRemoveTe xt will be sufficient (unless you
have variables with those names higher in the scope chain, which I
doubt is true).


Right again. I had already declared them as global variables so it was
also redundant.
I realize i could pass the addOnClick function by reference such as:
oFilterAdd.addE ventListener("c lick", this.addOnclick (), false);


That would be a function call, not a reference. In any case, it
wouldn't matter: addOnclick would be called as a member of

oFilterAdd.

Right again. It should have read:

oFilterAdd.addE ventListener("c lick", this.addOnclick , false);
A completely different approach would be to use a closure, avoiding
globals altogether (which is arguably better):


After reading all I could stomach about closure I worked up an example
that uses your example of using closure to reference properties and an
example of what I would like to do using prototyping.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>

<form id="form">
</form>

<script type="text/javascript">

function SortableTable() {
var filter = document.create Element('button ');
var filter_2 = document.create Element('button ');
var form = document.getEle mentById("form" );
var addText = document.create TextNode('Add') ;
var removeText = document.create TextNode('Remov e');
var addText_2 = document.create TextNode('Add') ;
var removeText_2 = document.create TextNode('Remov e');

filter.type = 'button';
filter_2.type = 'button';
form.appendChil d(filter);
form.appendChil d(filter_2);
filter.appendCh ild(addText);
filter_2.append Child(addText_2 );

//listener function reference is obtained as a private method using
closure
filter.addEvent Listener('click ', listener, false);
//proto_listener is a public method of SortableTable and a reference
// cannot be obtained using closure.
filter_2.addEve ntListener('cli ck', this.proto_list ener, false);

function listener(e) {
//this references button object
//addText/removeText are accesable as private properties
// via closure
this.removeChil d(addText);
this.appendChil d(removeText);
}
}

SortableTable.p rototype.proto_ listener = function (e) {
//this references button object
//addText_2/removeText_2 are not accesable as private properties
//via closure so an error is generated
this.removeChil d(addText_2);
this.appendChil d(removeText_2) ;
}

st = new SortableTable() ;

</script>
</body>
</html>

It seems that I will need to pass the scope of the SortableTable
instance to the proto_listener function.

I found this:

http://jibbering.com/faq/faq_notes/closures.html#clObjI

which seems to be an excellent solution to the scoping issues. It is a
bit of a mind bender (for me at least) but here is my own workup of the
authors example.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>

<script type="text/javascript">

function associateObjWit hEvent(obj, methodName){
//obj is the SortableTable instance
return (function(e){
e = e||window.event ;
//this refers to the event object
//when onclick occurs obj and methodName
//are still available because of closure
return obj[methodName](e, this);
});
}

function SortableTable(e lementId){
this.property = "foo"
var el = document.getEle mentById(elemen tId);
if(el){
el.onclick = associateObjWit hEvent(this, "doOnClick" );
}
}

SortableTable.p rototype.doOnCl ick = function(event, element){
//this scope has not changed so this.property is available
alert(this.prop erty);
alert(element);
element.id = "new_text"
alert(element.i d);
}

p = document.create Element("p");
p.id = "text";
text = document.create TextNode("text" );
document.body.a ppendChild(p);
p.appendChild(t ext);
obj = new SortableTable(" text");

</script>
</body>
</html>

Thanks for all the help and feel free to rip apart my logic and
terminology.

Derek Basch

Jul 23 '05 #3
Derek Basch wrote:

[snip]
After reading all I could stomach about closure
Closures aren't necessarily the easiest things to understand. At least
not at first. The specifics delve deep into the language and touch on
information that isn't really explained anywhere outside of the
language specification (a link is in the FAQ[1]). To make matters
worse, the specification is badly written in that it's difficult to
comprehend. It's not really surprising that closures aren't used that
often (intentionally) "in the wild".
I worked up an example that uses your example of using closure to
reference properties and an example of what I would like to do
using prototyping.
[snipped example]

It seems fine, aside from the problem you acknowledged. I'm surprised
my suggestion was useful - I thought I was missing too much information.

Is there any particular reason why you want to use prototyping? It is
for extensibility, or for some other purpose?
It seems that I will need to pass the scope of the SortableTable
instance to the proto_listener function.


To continue using "private" data, you have little choice but to use a
closure of some kind. It is impossible to directly "privilege" a
prototyped member. However, it is still possible to delegate to a
prototyped member:

function SortableTable(i d) {
/* Create a reference to the SortableTable object.
* This can be used in cases where the this operator
* will refer to something other than a SortableTable
* instance.
*/
var instance = this,
/* Initialise the rest of our private data. */
filter = document.create Element('button '),
addText = document.create TextNode('Add') ,
removeText = document.create TextNode('Remov e'),
element = document.getEle mentById(id);

/* Create a "privileged " function which can access
* the "private" data above and pass it to an
* unprivileged method.
*/
function listener() {
instance.doOnCl ick(this, removeText, addText);
}

filter.type = 'button';
filter.appendCh ild(addText);
filter.addEvent Listener('click ', listener, false);

element.appendC hild(filter);
}

/* add - Contains the node to be added
* remove - Contains the node to be removed
*/
SortableTable.p rototype.doOnCl ick = function(obj, add, remove) {
obj.removeChild (remove);
obj.appendChild (add);
};

If you needed to pass a lot of data, it might be more convenient to
place the "private" stuff in an object and pass that:

function SortableTable(i d) {
var data = {
addText : document.create TextNode('Add') ,
removeText : document.create TextNode('Remov e')
};

function listener() {
me.doOnClick(th is, data);
}
}

SortableTable.p rototype.doOnCl ick = function(obj, data) {
obj.removeChild (data.addText);
obj.appendChild (data.removeTex t);
};

Hope that helps,
Mike

[1] <URL:http://jibbering.com/faq/>

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4

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

Similar topics

6
3941
by: Csaba2000 | last post by:
How do I achieve the following in javascript, the emphasis being on the NN (6.1) 'event' parameter that needs to be declared? This is the current method - works just fine: <TABLE border id='myTable' onmouseover="tableMoused(event)"> But, because I may or may not want myTable subject to being "Moused", I want to have something like:
14
12154
by: JPRoot | last post by:
Hi I use the following syntax to have events inherited from base to child classes which works nicely (virtual and override keyword on events). But I am wondering if it is a "supported" way of using events since I never saw it used anywhere in MSDN documentation/samples?! Or it will just break when I upgrade to .NET Framework 2.x in the coming years namespace MyNamespac public delegate void MyDel() public class MyBase public virtual...
8
2897
by: JPRoot | last post by:
Hi M. Jeffrey Tan, Just hopping you didn't forget me? :) Thanks JPRoot ----- \"Jeffrey Tan\" wrote: -----
7
1981
by: Rakesh Rajan | last post by:
Hi, I find that when i define a delegate, it gets derived from MulticastDelegate, which provides all funtionality that events would provide (like registering new handlers etc.). Then, apart from being a bit more neater, could there have been any other reason that an 'event' keyword became necessary in C#? Thanks in advance, --
4
22891
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on when to use one over another? If anyone could provide any additional info, your comments, best practices, any good articles, specific examples, etc. Thank you
30
3660
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment it seems to me that Microsoft has developed similar functionality via two keywords. I do understand that an event offers better encapsulation as the underlying delegate is private, but is that all ? -- Regards
7
1469
by: Bruce | last post by:
I have a DotNet C++ class that I would like to fire an event to then be used by VB.Net using the With Events keyword. I have experience creating connection point events for ActiveX controls, it is actually very easy with the ATL wizard but I am lost when it comes to C++ .Net's events. Can anyone please point me to an example in VC++ .Net that allows me to then use the component in VB with the With Events keyword?
7
2345
by: mavigozler | last post by:
IE7 does not appear to set an event on contained text inside SPAN elements whose 'onclick', 'onmouseover', and 'onmouseout' events, defying the HTML recommendation. Firefox appears to conform. Is that so?
7
3423
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that uses the "WithEvents" and events. There is another example on page 124 that shows how to use delegates to sort an array. I don't understand the difference between events and delegates. Are they redundant features? How do I decide which to use? ...
0
9698
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
9556
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
10052
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...
1
7589
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
6829
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
5479
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
4156
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
2
3773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2959
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.