1

我正在使用以下代码将一个文本区域的输入复制到另一个文本区域中:

/**
 * 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

4

1 回答 1

5

当然!当你传递一个定义的函数代替匿名函数时,你省略(),否则这个函数将在编译后立即被调用。所以,改变

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

lOldDescription.addEventListener("keyup", linkListener, false);
                                                      ^^ bye bye ()
于 2013-11-13T01:52:50.800 回答