Ian Walker-Sperber
Ian Walker-Sperber

Reputation: 3799

Javascript event listening differs depending on use of anonymous or named function

I'm using the following code to duplicate the input of one textarea in another:

/**
 * Copies the values entered into the old description
 * into the new description, until the user focuses 
 * on the new description
 */
var DescriptionLinker = (function() {
    var elOldDescription,
        elNewDescription,
        linkIsBroken;

    this.init = function() {
        console.log('Initializing DescriptionLinker');
        elOldDescription = document.getElementById("old-description");
        elNewDescription = document.getElementById("new-description");
        linkIsBroken = false;

        linkDescriptions();
        watchLinkBreak();
    }

    // Assigns values to 'this'
    var finalize = function() {
        this.elOldDescription = elOldDescription;
        this.elNewDescription = elNewDescription;
    }

    var linkDescriptions = function() {
        elOldDescription.addEventListener("keyup", linkListener(), false);
    }

    var unlinkDescriptions = function() {
        elOldDescription.removeEventListener("keyup", linkListener(), false);
    }

    var linkListener = function(){
        elNewDescription.value = elOldDescription.value;
    }

    var watchLinkBreak = function() {
        console.log("Watching for link break");
        elNewDescription.addEventListener("focus", function(){
            unlinkDescriptions();
        });
    }

    finalize();
    return this;
})();

DescriptionLinker.init();

The code works, however the values do not appear in <textarea id="new-description"></textarea> until I focus on the text area. If I replace the call to linkerfunction() with an identical anonymous function then the values correctly appear in the new-description textarea as I type in the old-description. Any ideas why?

To clarify, the following works correctly:

var linkDescriptions = function() {
    elOldDescription.addEventListener("keyup", function(){ 
         elNewDescription.value = elOldDescription.value;
    }, false);
}
var unlinkDescriptions = function() {
    elOldDescription.removeEventListener("keyup", function(){ 
         elNewDescription.value = elOldDescription.value;
    }, false);
}

PS reason for all this is transition from a legacy system :p

Upvotes: 1

Views: 44

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Of course! When you pass a defined function in place of an anonymous function, you omit the (), else this function will be called as soon as it is compiled. So, change

lOldDescription.addEventListener("keyup", linkListener(), false);

To

lOldDescription.addEventListener("keyup", linkListener, false);
                                                      ^^ bye bye ()

Upvotes: 5

Related Questions