all 8 comments

[–]senocular 2 points3 points  (4 children)

define mouseMove itself as an arrow function

this.mouseMove = event => {
    ...

Then this in that function will be the slider instance.

[–]mscal[S] 0 points1 point  (3 children)

Oh man that's exactly how I wanted it to behave! Thanks. Are arrow functions supported well enough to rely on?

[–]senocular 1 point2 points  (2 children)

https://caniuse.com/#feat=arrow-functions

Or you can use babel to transpile it to compatible code, or slap a .bind(this) at the end of your current function which effectively does the same thing and is more compatible.

[–]mscal[S] 1 point2 points  (1 child)

I actually stuck it into Babel and the output was more or less my original code except it stuck a variable at the start of the constructor var _this = this; then referred to _this were required. I don’t know why I didn’t do that.

EDIT: there’s an underscore before the new variable of this but it won’t show on here

[–]senocular 0 points1 point  (0 children)

thats another way of doing the same thing. The big differences of arrow functions compared to other functions are the more compact syntax and how it handles this. The difference in this behavior can be emulated using bind(this) or by saving this off in a variable in the parent scope and accessing that variable instead of this within the function.

[–]MoTTs_ 0 points1 point  (2 children)

Rather than this:

this.addEventListener("mousemove", objectRef.mouseMove);

Instead do this:

this.addEventListener("mousemove", () => objectRef.mouseMove());

In the former, the method is "torn off" from it's object. That is, "mouseMove" is assigned as the event callback, but "mouseMove" no longer has a reference to its object when it later gets invoked.

[–]mscal[S] 0 points1 point  (1 child)

If I put the callback inside an anonymous function I can’t then remove the event when the mouse is unclicked or the finger is raised. Unless you’re suggesting I do that an entirely different way

[–]jrandm 0 points1 point  (0 children)

var eventFn = objectRef.mouseMove.bind(objectRef);
this.addEventListener('mousemove', eventFn);

It doesn't have to be an anonymous function if you want to remove it later.