0

I am new in OOP in Javascript, I wanted to have my Slider object with its own attributes and methods. It works fine until I add the Eventlistener with my method slideNextImage. Once this method is triggered every attribute inside the method is undefined. If I launch the method without attaching any event it works good.

function Slider(photos, currentPhoto){ //Constructor
    this.photos = photos;
    this.currentPhoto = currentPhoto;
}

Slider.prototype.slideNextImage = function () {
    document.getElementById("slider").style.backgroundImage = "url(" + this.photos[this.currentPhoto] + ")";
    console.log("La foto actual es la " + this.currentPhoto + " y en el almacen hay " + this.photos.length);
}

var photos = ["../imagenes/images/wallpaper_5.jpg", "../imagenes/images/wallpaper_4.jpg", "../imagenes/images/wallpaper_3.jpg", "../imagenes/images/wallpaper_2.jpg", "../imagenes/images/wallpaper_1.jpg"];

var slider = new Slider(photos, 0);

document.getElementById("next").addEventListener("click", slider.slideNextImage);

Thank you in advance.

Juan Manuel Amoros
  • 347
  • 1
  • 5
  • 17

2 Answers2

2

Thats because 'this' is not bound to the object you really want in this case. (in your case 'this' will be bound to the element on which the event had been triggered)

One way to solve it is by explicitly bind 'this' to the slider by changing the addEventListener line to:

document.getElementById("next").addEventListener("click", Slider.prototype.slideNextImage.bind(slider));
Jumpa
  • 878
  • 1
  • 8
  • 12
1

Your method loses its context when called as an event handler (this is no longer your slider object). You have a couple of options, the simplest is to use Function.prototype.bind:

slider.slideNextImage.bind(slider);
Jared Smith
  • 19,721
  • 5
  • 45
  • 83