By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,818 Members | 2,089 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,818 IT Pros & Developers. It's quick & easy.

passing this to a event function

P: n/a

i've got this for IE:

node.onchange = foo;

but really i'd like to pass node object to foo function also.

in html i would do onchange="foo(this)"...but this has to
be done in javascript at runtime.

Aug 29 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
ppcguy wrote:
i've got this for IE:

node.onchange = foo;

but really i'd like to pass node object to foo function also.

in html i would do onchange="foo(this)"...but this has to
be done in javascript at runtime.
You don't need to as - this - inside - foo - will already refer to your
- node - object when it is called as the onclick handler for - node -.

This works because when in HTML you do:-

<X onclick="foo(this);">

- the browser used the string value of the onclick attribute as the
body for a function it creates internally and assigns to the - onclick
- property of the element. So the above is equivalent to:-

node.onclick = function(){
foo(this);
};

(where - node - refers to the element that would have the onclick
attribute otherwise). And then when the browser responds to a click
event it calls this function assigned to the - onclick - property of
the element as a method of the element so - this - refers to the
element.

Richard.

Aug 29 '06 #2

P: n/a
ppcguy wrote:
i've got this for IE:

node.onchange = foo;

but really i'd like to pass node object to foo function also.

in html i would do onchange="foo(this)"...but this has to
be done in javascript at runtime.
function foo(){
var theNode = this;
}

When you do:

node.onchange = foo;

the value of node's onchange attribute is assigned a reference to foo, a
function object. Effectively you you have:

node.foo

When you fire node's onchange event, foo is called like this:

node.onchange();

which is (more or less) the same as:

node.foo();

so that foo's 'this' operator will reference 'node'.

If you just call foo(), you are effectively calling window.foo() and its
this operator will reference the window/global object.
--
Rob
Aug 29 '06 #3

P: n/a
ppcguy wrote:
i've got this for IE:

node.onchange = foo;

but really i'd like to pass node object to foo function also.
Event listeners assigned in that manner are called as properties of the
node, therefore the value of the this operator already /is/ a reference
to the element.

Using the addEventListener method (W3C DOM) will also cause the this
operator to be set to the element, but with the attachEvent method (MSIE
DOM), the operator will refer to the global object.

[snip]

Mike
Aug 29 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.