如何将其他对象插入事件监听器?

时间:2014-05-12 11:30:47

标签: javascript event-handling

这是我的javascript:

var tool = {
    addEvent : function(element, eventName, callback){
        if (element.addEventListener) {
            element.addEventListener(eventName, callback, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + eventName, callback);
        }          
    },
    getPosition : function(el){
        var _x = 0;
        var _y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
            _x += el.offsetLeft - el.scrollLeft;
            _y += el.offsetTop - el.scrollTop;
            el = el.offsetParent;
        }
        return { top: _y, left: _x };
    }
}
function getObj(){
    this.a = document.getElementById('div');
    this.b = document.getElementById('table');


    this.func = function(){
        var pos = tool.getPosition(this);
        // how to insert this.b here
        // i want to set this.b offset from this.a offset
    }

    tool.addEvent(this.a,'scroll',this.func);
}

var obj = new getObj();

如何修改this.func所以每当this.a滚动时,this.b将同步​​到this.a
this.b offset来自this.a offset。

当我尝试:

 this.func = function(){
        var pos = tool.getPosition(this);
        // value from pos will be set to this.b
        console.log(this.b);
        // how to insert this.b here
        // i want to set this.b offset from this.a offset
 }

this.b未定义。

1 个答案:

答案 0 :(得分:0)

您的getPosition功能是this的成员,因此您无法使用getPosition(...)来呼叫它。您必须使用this.getPosition(...)调用它或将getPosition函数重新声明为函数范围变量:

function getObj() {
    ...
    var getPosition = function(...) { ... };

    this.addEvent = function(...) { ... };
    ...
}

编辑:

添加DOM事件时,您还需要将this.func绑定到当前上下文:

this.func = this.func.bind(this);

this.addEvent(this.a, '滚动',this.func);