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

Passing parameters to event handler

Hallo,

I have been programming for restricted environments where Internet Explorer
is a standard, so I haven't stumbled upon this problem until now, when I
need to write a DOM-compatible code.

The question is about best practices for passing parameters to an event
function.

I have, say, the following HTML:

<div onclick="myEventHandler()">Here's some text</div>

and here's the event handler function:

function myEventHandler(evt) {
evt = (evt) ? evt : ((event) ? event : null); // to get single interface
to the IE event object or the DOM event object.
// Now must handle the event
}

In the example case, the event handler is written directly in the html code,
or the strings is outputed with document.write or element.innerHTML is
assigned. However, in more general way, my application framework allows also
to snap that event to most any tag and still the handling should be exatly
as defined. There are no multiple handler functions, the behaviour is
determined by the function that took care for attaching the event. That
means, I *have* to pass some parameters with the handler function call. In
IE that ie easy, as I have no requirement to provide a single argument to
the handler function that is filled with event object. I can freely write
onclick="myHandler(123)" and it works fine. Now, I see some approaches to
handle this parameter passing problem. One is assigning the parameters to
some global variable and then accessed from within the event handler
function:

onclick="parms={a:1, b:2}; myHandler()"

function myHandler() {
alert(parms.a + "; " + parms.b);
}

it's ugly, since I dont like that function refers to external global
variable parm, but it works. However I am not sure if the values of
parameters are persistent while the event handler and all the function call
chain is processed.

So, maybe there is some standard approach practised among ECMAscript
developers?

Thanks,
-Pavils Jurjans
Jul 20 '05 #1
7 49534
Yep
pa****@mailbox.riga.lv (Pavils Jurjans) wrote in message news:<95**************************@posting.google. com>...
The question is about best practices for passing parameters to an event
function. <div onclick="myEventHandler()">Here's some text</div> function myEventHandler(evt) {
evt = (evt) ? evt : ((event) ? event : null); // to get single interface
to the IE event object or the DOM event object.


Better to use the following in such situations:
evt=evt||window.event;
Javascript's "||" operator is much more powerful than generally
assumed by (non-js) programmers - Ecma refers.
In the onclick attribute (which, to js, is an anonymous function) the
event object is available as "event", so you can just pass it to the
internal handler (in IE you'll pass the global event object, which is
fine).

<div onclick="func(event,'World')">Hello...?</div>
<script type="text/javascript">
function func(evt, s){
alert(s+" (from "+(evt.srcElement||evt.target).nodeName+")");
}
</script>
That's the easy way; just for fun, here's another way (not really
recommendable, but much more enjoyable):

<div onclick="func2('World')">Hello...?</div>
<script type="text/javascript">
function func2(s){
var evt = window.event || function(cx) {
if(typeof Event!="undefined" && cx){
for(var ii=0; ii<cx.arguments.length; ii++)
if(cx.arguments[ii] instanceof Event)
return cx.arguments[ii];
return arguments.callee(cx.caller);
}
return null;
}(arguments.callee.caller);

alert(s+" (from "+(evt.srcElement||evt.target).nodeName+")");
}
</script>
Regards,
Yep.
Jul 20 '05 #2
Hallo Yep,

The first method is the one I was looking for, I didn't know that in the
scope of event handler attribute the "event" object is available in non-IE
platforms.

The other method certainly is certainly charming :) The syntax used kinda
tells what kind of 'compact javascript' lover you are ;)

What regards the use of "logical OR" operation for determining the "first
available non-false/null/undefined item in the chain, it's a nice trick. I,
also being lover of compactness, appreciate this hint, however it may reduce
the readability of my code for other programmers. It's a surprise for me
that the operands of "logical OR" operation are not internally converted to
booleans prior to executing the operation. I am not sure how standard is
this behaviour, and I am cautious if this isn't a hack that may not be
present in some JavaScript environment that strictly follows the ECMA262
guidelines. In the book what I use for referring JavaScript queries
(O'Reillys' JavaScript the definitive Guide 3rd ed.), there is no hint about
the use of "logical OR" for returning non-boolean variable types. How sure
one can be it's the feature here to stay?

-- Pavils Jurjans
Jul 20 '05 #3
"Pavils Jurjans" <pa****@mailbox.riga.lv> wrote in message
news:95**************************@posting.google.c om...
<snip>
What regards the use of "logical OR" operation for determining
the "first available non-false/null/undefined item in the chain,
it's a nice trick. I, also being lover of compactness, appreciate
this hint, however it may reduce the readability of my code for
other programmers.
You would let the limitations of another language restrict your
JavaScript? Would those other programmers put up with their
non-JavaScript code being limited to only include structures that made
sense in JavaScript?
It's a surprise for me that the operands of "logical OR" operation
are not internally converted to booleans prior to executing the operation.

They are, at least the left hand operand is, but that internal boolean
value is never the result of the expression.
I am not sure how standard is this behaviour, and I am cautious
if this isn't a hack that may not be present in some JavaScript
environment that strictly follows the ECMA262 guidelines.
<quote cite="ECMA 262 3rd edition Section 11.11">

The production LogicalORExpression : LogicalORExpression ||
LogicalANDExpression is evaluated as follows:

1. Evaluate LogicalORExpression.
2. Call GetValue(Result(1)).
3. Call ToBoolean(Result(2)).
4. If Result(3) is true, return Result(2).
5. Evaluate LogicalANDExpression.
6. Call GetValue(Result(5)).
7. Return Result(6).

</quote>

Notice that ECMA 262 requires that the result of the expression be the
result of a call to the internal GetValue function and not the result of
the call to ToBoolean on which the decision about which operand to
return is made.
In the book what I use for referring JavaScript queries (O'Reillys'
JavaScript the definitive Guide 3rd ed.), there is no hint about
the use of "logical OR" for returning non-boolean variable types.
JavaScript the definitive Guide might be the best book on JavaScript
available but it still does not cover much of the really interesting
stuff. (Does it mention closures?)
How sure one can be it's the feature here to stay?


It is ECMA 262 Specified, so it is here to stay.

Richard.
Jul 20 '05 #4
Hallo Richard,

Your reference to ECMA spec set's it straight and safe
JavaScript the definitive Guide might be the best book on JavaScript
available but it still does not cover much of the really interesting
stuff. (Does it mention closures?)


I was somewhat mistaken claiming that it doesn't provide hint on that
specific functionality. It actually does, but doesn't provide explicit
examples, so I missed it. Yes, the book covers closures, and does it
in quite detailed manner. It doesn't focus too much on OO-patterns,
but then again it's not that JavaScript oriented topic, but rather
than general programming one.

Rgds,

-- Pavils Jurjans
Jul 20 '05 #5
"Pavils Jurjans" <pa****@mailbox.riga.lv> wrote in message
news:95**************************@posting.google.c om...
The first method is the one I was looking for, I didn't know
that in the scope of event handler attribute the "event"
object is available in non-IE platforms.

<snip>

It might be worth explaining why - event -, as an identifier, works in
both Netscape/Gecko and IE even though they handle the referencing of
event objects differently.

It works like this, given the example HTML:-

<input onblur="doSomething(this, event);"
type=""text""
name="anyName">

- the browser takes the string that is provided as the value for the
onblur attribute and uses that string as the function body for an
anonymous function that it creates (internally) as an onblur event
handling method for the input element. On Netscape browsers it is the
equivalent of doing this in javascript:-

document.forms['aForm'].elements['anyName'].onblur = function(event){
doSomething(this, event);
}

- notice that the internally created function has a parameter with the
identifier - event - . IE produces an anonymous function like:-

document.forms['aForm'].elements['anyName'].onblur = function(){
doSomething(this, event);
}

- with no specified parameter. The practical result is that any use of
the identifier - event - within the string assigned to an event handling
attribute in HTML will refer to the event object because in
Netscape/Gecko browsers it refers to the automatically generated and
named function parameter - event - and on IE it is resolved as the
global - event - object.

The same is not true of event handling functions defined with JavaScript
and then assigned to event handling properties (or with
addEventListener) as if those functions are defined with - event - as
the identifier for their first parameter the use of the identifier -
event - within the function body can only refer to that parameter,
though the IE global event object could still be more explicitly
referenced with - window.event _. But it is normal to give the first
parameter of such a function a different identifier and then use the
logical OR construct to normalise it to refer to which ever event object
was available.

Richard.
Jul 20 '05 #6
"Pavils Jurjans" <pa****@mailbox.riga.lv> wrote in message
news:95**************************@posting.google.c om...
<snip>
... . It doesn't focus too much on OO-patterns,
but then again it's not that JavaScript oriented
topic, but rather than general programming one.


If you are interested in JavaScript OO it would be worth having a look
at what Douglas Crockford has to say on the subject (particularly
inheritance and emulating private instance members on JS objects).

<URL: http://www.crockford.com/ >

Richard.
Jul 20 '05 #7
Thanks a lot Richard. You really cleared things up for me :)
Jul 8 '06 #8

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

Similar topics

2
by: StvB | last post by:
Hi, I'm now trying to separate my wxPython GUI-building code into different files, and ran into a bump: In main.py, I add an event handler to a list: ---------------------- # -- add the event...
3
by: N. Demos | last post by:
How do you dynamically assign a function to an element's event with specific parameters? I know that the code is different for MSIE and Mozilla, and need to know how to do this for both. I...
2
by: Omar | last post by:
Hi! I have a JavaScript function that receives an Array with words. This Array can be gotten from a query to a DB using JSP. The JavaScript function is executed when onFocus event occurs:...
2
by: Fei | last post by:
HI, I have a problem about EventHandler. I have a form with one button on it. I implement Button's click event. Is there a way I can determine whether I implement a handler for this event at...
10
by: Fao, Sean | last post by:
A guy I know never refactors his code and insists on putting everything in an event handler. For example, he does some initialization of a DataGrid in the ItemDataBound event handler (which is...
5
by: james | last post by:
Hello, I am having a little trouble creating an event handler for a context menu toolstripmenuitem. I've seen various tutorials and so on, but I keep getting a bit stuck! So far I have a second...
7
by: Andrus | last post by:
I noticed that DataGridView CellValidated() and other event handler first parameter is object: Grid.CellValidated+=new DataGridViewCellEventHandler(Grid_CellValidated); .... void...
4
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi, just wondering if anyone can provide a brief example of passing parameters from one webpage to another, C# VS2005? I need to pass several selected values of dropdown list boxes to a secondary...
24
by: =?Utf-8?B?U3dhcHB5?= | last post by:
Can anyone suggest me to pass more parameters other than two parameter for events like the following? Event: Onbutton_click(object sender, EventArgs e)" Event handler: button.Click += new...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.