Ian*_*ber 1 javascript events dom
我正在使用以下代码复制另一个textarea的输入:
/**
* 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();
Run Code Online (Sandbox Code Playgroud)
代码有效,但是在<textarea id="new-description"></textarea>我专注于文本区域之前,值不会出现.如果我用linkerfunction()相同的匿名函数替换调用,那么new-description当我输入时,值正确地出现在textarea中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);
}
Run Code Online (Sandbox Code Playgroud)
所有这一切的PS原因是从遗留系统过渡:p
当然!当您传递一个已定义的函数来代替匿名函数时,您省略了(),否则只要编译它就会调用此函数.所以,改变
lOldDescription.addEventListener("keyup", linkListener(), false);
Run Code Online (Sandbox Code Playgroud)
至
lOldDescription.addEventListener("keyup", linkListener, false);
^^ bye bye ()
Run Code Online (Sandbox Code Playgroud)