JS:如何在事件监听器中设置闭包?

时间:2015-03-24 04:25:55

标签: javascript

我一直在阅读很多关于闭包的内容,但仍然很难抓住它们。我试图通过每次用户滚动时向元素的top样式属性添加动态确定的像素数来获得视差滚动功能。

var parallaxApp = {

    publicVars = {},

    addListeners: function() {
        window.addEventListener("scroll", parallaxApp.setHeight, false);
        //more listeners would go here
    },

    //this function is invoked every time the user scrolls
    setHeight: function() {            
        var height = parallaxApp.publicVars["set height"]; //34

        //every time setHeight is invoked I want to add 34
        return function() {

            //how can I store this local variable outside of the execution of its scope?
            height = height + parallaxApp.publicVars["set height"]; //34, 68, 102, etc.
            document.getElementById("someDiv").style.top = height+"px";
        } 
    },

    run: function() {  

        //set public variables
        for (var arg in arguments[0]) {
            parallaxApp.publicVars[arg] = arguments[0][arg];
        }

        //once the page loads, attach various listeners to the window object
        window.addEventListener("load", parallaxApp.addListeners, false);
    }

}

parallaxApp.run({"set height": 34});

因为我在通过事件监听器实例化的每个滚动上调用一个函数,所以我对如何设置我的作用域感到困惑。通过在publicVars的每次调用中修改setHeight“public”变量来实现此目的的唯一方法是什么? (也没有jquery请)

1 个答案:

答案 0 :(得分:0)

由于setHeight正在返回实际的滚动事件处理程序,因此需要调用setHeight函数,以便将其返回的函数设置为处理程序

window.addEventListener("scroll", parallaxApp.setHeight(), false);

此外,您不应修改闭包变量height

setHeight: function() {            
    var height = parallaxApp.publicVars["set height"]; //34

    //every time setHeight is invoked I want to add 34
    return function() {

        //how can I store this local variable outside of the execution of its scope?
        var xheight = height + parallaxApp.publicVars["set height"]; //34, 68, 102, etc.
        document.getElementById("someDiv").style.top = xheight +"px";
    } 
}