我正在使用以下代码将一个文本区域的输入复制到另一个文本区域中:
/**
* 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();
<textarea id="new-description"></textarea>
代码有效,但是在我关注文本区域之前,这些值不会出现。如果我将调用替换为linkerfunction()
相同的匿名函数,那么new-description
当我在old-description
. 任何想法为什么?
为了澄清,以下工作正常:
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 这一切的原因是从遗留系统过渡:p