Reputation: 1783
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
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