0
class SwipeController {
  constructor(threshold) {
    var myElement = document.getElementById('swipecontainer');


    myElement.width = $( window ).width();
    myElement.height = $( window ).height();

    var mc = new Hammer(myElement);
    mc.get('pan').set({ direction: Hammer.DIRECTION_ALL, threshold: threshold });

    this.swiperight = new Array();
    this.swipeleft = new Array();
    mc.on("panright", function(ev) {
      alert(this.swiperight)
    this.swiperight.forEach(function(func) {

      func();
    })
    });

     mc.on("panleft", function(ev) {
      this.swipeleft.forEach(function(func) {
        func();
      })
    });

  }

  set swipeRight(value) {
      this.swiperight.push(value)
  }

  set swipeLeft(value) {
      this.swipeleft.push(value)
  } 
}

module.exports = SwipeController;

I realize that alert(this.swiperight) is showing as undefined because "this" is no longer the SwipeController class. How do I go about doing this? I'm trying to make this event trigger to trigger ANY event i connect to it, so I can handle all my swipe detection from one class.

Cody
  • 149
  • 1
  • 10
  • Use an arrow function, bind the this context to the function or create a variable referencing this in the class itself, in order of personal preference ;) – Icepickle Oct 12 '17 at 22:43
  • Thanks for the life saver, I guess I couldn't word the question right and find the duplicate! – Cody Oct 12 '17 at 23:12

1 Answers1

0

This is due to the fact that the this context of the callback is no longer the object of the class, but the object triggering the event. To overcome this issue you can define a variable just before the callback definition that points to this and use it inside the callback (thus not incurring in this 'name conflict'):

var _this = this;
mc.on("panright", function(ev) {
    alert(_this.swiperight);
    _this.swiperight.forEach(function(func) {
        func();
    });
});

mc.on("panleft", function(ev) {
    _this.swipeleft.forEach(function(func) {
        func();
    });
});
Roberto Trani
  • 1,217
  • 11
  • 14
  • well, the arrow function is so much easier ;) Seeing he uses constructors and classes already, I don't think that would be a problem for the OP. Btw, that's one of the top duplicate questions in javascript ;) – Icepickle Oct 12 '17 at 22:53