Thomas 'PointedEars' Lahn wrote:
> Andrew Poulos wrote:
>> I have code that looks like this
>>
>> function elementOver() {
>> return function() {
>> this.style...
>> };
>> }
>>
>> function setOver(elem) {
>> for (var i = 0; elem.length; i++) {
>> elem[i].addEventListener("mouseover", elementOver() );
>> }
>> }
>>
>> function disableOver(elem) {
>> for (var i = 0; i < elem.length; i++) {
>> elem[i].removeEventListener("mouseover", elementOver() );
>> }
>> }
>>
>> Adding the listener works but removing it doesn't. I don't understand
>> why not nor how to remove the listeners?
>
> Every time you call elementOver(), you create a *new* Function instance
> and return a reference to *that*.
This answers the “why not” part of your question.
The answer to the “how” part (which I noticed only now) may not be obvious
if you could not find the answer to the “why not” part by yourself:
You need to store references to the listeners so that you can reuse them.
/*
* NOTE:
* Easily maintainable code uses _plurals_ in the names of iterables
*/
var elementOvers = [];
function setOver (elements)
{
/*
* NOTE:
* You may want to use ES 5 [].forEach.apply(elements, …) or
* ES 6 “for … of” on [].slice.call(elements) instead.
*
* In loops, cache the value of the “length” property unless you
* expect its value to change and want to handle that.
*/
for (var i = 0, len = elements.length; i < len; ++i)
{
/* NOTE:
* You can still return the function reference instead.
* Just keep in mind that in the way it is used here,
* there is a closure over “i”.
*
* Consider using CSS “:hover” selectors based on class selectors
* instead of setting style properties here.
*/
var elementOver = elementOvers[i] = function () {
this.style...
};
/* NOTE: The third argument may not be “false” by default. */
elements[i].addEventListener("mouseover", elementOver, false);
}
}
function disableOver (elements)
{
for (var i = 0, len = elements.length; i < len; ++i)
{
elements[i].removeEventListener("mouseover", elementOvers[i]);
}
}
Usually one implements an event registry object for this purpose (which,
if the built-in Map object is supported, can register event listeners per
element object even without using additional identifying properties now,
and certainly without host object augmentation), and one does not use many
user-defined *global* variables and functions.
HTH.