Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript event listening differs depending on use of anonymous or named function
    text
    copied!<p>I'm using the following code to duplicate the input of one textarea in another:</p> <pre><code>/** * 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(); </code></pre> <p>The code works, however the values do not appear in <code>&lt;textarea id="new-description"&gt;&lt;/textarea&gt;</code> until I focus on the text area. If I replace the call to <code>linkerfunction()</code> with an identical anonymous function then the values correctly appear in the <code>new-description</code> textarea as I type in the <code>old-description</code>. Any ideas why?</p> <p>To clarify, the following works correctly:</p> <pre><code>var linkDescriptions = function() { elOldDescription.addEventListener("keyup", function(){ elNewDescription.value = elOldDescription.value; }, false); } var unlinkDescriptions = function() { elOldDescription.removeEventListener("keyup", function(){ elNewDescription.value = elOldDescription.value; }, false); } </code></pre> <p>PS reason for all this is transition from a legacy system :p</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload