Malibur
Malibur

Reputation: 1783

OO Javascript, calling prototype function from constructors addEventListener

Im trying to set up an object, and when i make an instance of that object, id like to add an EventListener to a specific object. But it throws me an exception stating

Uncaught TypeError: Object #<HTMLDivElement> has no method 'nextSlide'

I have the following code

//Constructor function
function CinnamonSlider (sliderID) {
// Settings - must be set. 
    this.sliderID = sliderID;   

    var nextController = document.querySelector('.'+this.sliderID+'-next');

    nextController.addEventListener("click", function(e) {
        this.nextSlide();
        e.preventDefault();
    });

}

CinnamonSlider.prototype.nextSlide = function() {
    console.log('next');
};

var mySlider = new CinnamonSlider('my-slider');

What am i doing wrong here??

Thanks!

Upvotes: 0

Views: 673

Answers (1)

adeneo
adeneo

Reputation: 318222

this inside the event handler is the element, not the class. Store the value of this in a variable

function CinnamonSlider (sliderID) {

    this.sliderID = sliderID;   

    var nextController = document.querySelector('.'+this.sliderID+'-next');

    var self = this;

    nextController.addEventListener("click", function(e) {
        self.nextSlide();
        e.preventDefault();
    });

}

CinnamonSlider.prototype.nextSlide = function() {
    console.log('next');
};

var mySlider = new CinnamonSlider('my-slider');

Upvotes: 3

Related Questions