Search code examples
javascriptinteract.js

how to call this with libraries that changing the default this?


so I started to using interactjs and I have this simple code:

class example {
    registerTouchEvents() {
        var self = this;
        interact('.touchy').draggable({
            onstart: self.onStart,
        });
    }

    onStart(event) {
        this.someAction();//<-- not working as this is interact object
    }

    someAction() {
        console.log('touch has been started') //<-- I need to call this function
    }

}

is there someway of calling the current object without using global variable?


Solution

  • Move the handler where you declare "self":

    class example {
        registerTouchEvents() {
            var self = this
              , onStart = function onStart(event) {
                    self .someAction();
                }
              ;
            interact('.touchy').draggable({
                onstart: onStart,
            });
        }
    
        someAction() {
            console.log('touch has been started') //<-- I need to call this function
        }
    
    }