Javascript将事件监听器绑定到类

时间:2016-05-25 12:59:35

标签: javascript scope bind

是否可以添加事件侦听器并将其绑定到Object的实例(JS类)。

我正在编写一个Parallax库,用于当用户将鼠标悬停在div上时,我的应用程序的这部分工作正常,但我希望能够向主体添加滚动事件以将元素缩放为用户滚动。

我的JS课程内部有:

var InteractiveParallax = function(props)  {
    this.initialise(props);
};

InteractiveParallax.prototype.initialise = function(props) {
    var _this = this;
    _this.state = {
        type : props.type,
        target : props.target,
        ... // Other state here
    };

    // I want to bind the event listener here
    window.addEventListener("scroll", _this.zoomElement);
};

// THE METHOD I WANT TO CALL WHEN SCROLLING
InteractiveParallax.prototype.zoomElement = function(e) {
    console.log(this.state);
    var elem = document.querySelector(this.state.target);
    if(elem) {
        var offsetTop = body.offsetTop;
        this.transitionElement();  // update the element
    }
};

现在我在.zoomElement函数中获得this.state.target undefined。我猜这是因为当前状态没有绑定到我的对象的范围。

如何绑定到此对象实例的上下文,以便我可以访问状态?

0 个答案:

没有答案