On 19/06/2005 20:02, VK wrote:
[snip]
(1) <... onclick="myFunction(this);">
I wasn't referring to that one.
[snip]
(2) document.getElementById('myElement').addEventListener(
'click',
function() {
/* The this operator refers to the HTML element, myElement */
},
false
);
A closure I just mentioned.
That isn't a closure. That is two function calls with a string argument
passed in the first call, and a string, function expression, and boolean
passed in the second.
If this code is executed in a function then the function expression will
become an inner function and, as it survives after the outer call
returns, it will form a closure. However, that isn't an issue in itself
and, as written...
....the problem in IE that you refer to will not occur.
Given a more realistic implementation:
function listener(e) {
/* Some event listener */
}
function addListener(elementId) {
var element;
if(document.getElementById) {
element = document.getElementById(elementId);
}
if(element && element.addEventListener) {
element.addEventListener('click', listener, false);
}
}
there is still no problem as a closure isn't necessary. Altering it
slightly to use a closure (because sometimes they are necessary):
function addListener(elementId) {
var element;
if(document.getElementById) {
element = document.getElementById(elementId);
}
if(element && element.addEventListener) {
element.addEventListener('click', function(e) {
/* Some event listener */
}, false);
}
}
we now do have the potential for a memory leak in IE because the
reference in element will persist. However, that is trivial to deal with:
function addListener(elementId) {
/* ... */
element = null;
}
No circular reference. No memory leak.
Even if element had to remain for the benefit of something else (for
example, it's a private member in an object) the reference can be
cleared when the unload event is fired, so we still don't have a problem.
(3) document.getElementById('myElement').onclick = function() {
/* The this operator refers to the HTML element, myElement */
};
Anonymous functions... May get really ugly in big projects.
The use of a function expression was for my convenience, just as it was
with the addEventListener example in my previous post. Nothing prevents
the use of function declarations, or function expressions assigned to
identifiers.
Also forget about reusable .js libraries you could use in your code.
I have no idea what makes you think that, unless you're using some badly
designed libraries.
Of course you could wrap named functions, [...]
What!?
[snip]
So (2) and (3) may be used by OP unless "this and that". Should be
close the topic?
Perhaps you should just refrain from commenting on it until you know
what you're talking about. I'm sorry for being so harsh, but from
experience in previous threads, you seem incapable of understanding the
issues. Maybe I'm not providing decent explanations, but if that's the
case, you've never said anything to help me help you.
Mike