0

this is my 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();

how to modify this.func so whenever this.a is scrolling, this.b will be syncronized to this.a
this.b offset is get from this.a offset.

when i try :

 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 is undefined.

kreamik
  • 609
  • 2
  • 11
  • 24
  • i still cannot insert this.b to my func, could you help me @Bergi ?? – kreamik May 13 '14 at 02:24
  • 1
    `tool.getPosition(e.target)` and `tool.addEvent(…, this.func.bind(this))` should be working – Bergi May 13 '14 at 02:36
  • just for my knowledge, how to change bind to call @Bergi, bind work awesome but call only work on once, but call will not work for next scroll. – kreamik May 13 '14 at 02:45
  • 1
    What do you mean? `(function(context){return function(e){return context.func.call(context,e);};}(this))`? – Bergi May 13 '14 at 02:50
  • haha work great and awesome .. now it work to my IE6 @Bergi , how to appreciate your answer? i want to accept it. – kreamik May 13 '14 at 04:06

1 Answers1

0

Your getPosition function is a member of this, so you cannot call it using getPosition(...). You must call it using this.getPosition(...) or redeclare the getPosition function as a function scope variable:

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

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

Edit:

When adding the DOM event, you'll also need bind this.func to the current context:

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

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

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
  • i update my question, i want help particularly, how to insert this.b to my this.func @Greg Burghardt ? – kreamik May 13 '14 at 02:25