0

I'm new to javascript/jQuery.

I am doing a simple fade slider to use on a page, and I'm trying to put as much as I can inside the object, so it works out of the box whenever I create a new instance of the object. While setting up the navigation, I first did the following:

testimonial = new slider($('.testimonials'), $('.testimonials-nav'));
testimonial.nav.on('click', function (e) {
testimonial.setCurrent($(this).data('dir')); // changes the current slider
testimonial.transition(); // what happens when the 'current' changes
testimonial.setHeight(); //because everything is 'position: absolute', I set the parent div height with js
e.preventDefault();
});

But that way I'd need to repeat all this code everytime I create a new instance of the slider, so I tried a different approach, I created two methods:

slider.prototype.init = function () {
    this.numberEls();
    this.setHeight();
    this.activateNav();
};

so when I create a new instance I can do the following

testimonial = new slider($('.testimonials'), $('.testimonials-nav'));
testimonial.init();

and created this method

slider.prototype.activateNav = function () {
    this.nav.on('click', function (e) {        
        this.setCurrent($(this).data('dir'));
        e.preventDefault();
    });
};

but it doesn't work obviously because of the scope of the "this" keyword inside the event handler, how do I make the "this.setCurrent" work in this context?

Another question, overall, is it a good approach for what I'm trying to accomplish? remember that it might be used in other parts of the site, not only in testimonials.

And if it's not too much to ask, how could I make it loops automatically? I know it involves setTimeOut() or something, but I don't know exactly how (I need to be honest and say it's a lazy question, I actually didn't even try to do it before asking how, but since I am here =P)

Heres the fiddle

PS. I'm sorry if I didn't make myself clear, english is not my first language and I struggle with it sometimes =P

Daniel Ortiz
  • 901
  • 2
  • 7
  • 14
  • I do not think this is a duplicate because the issue isn't your treament of the "this" object specifically, rather it is as a result of using the JQuery "this" and the object "this" in the same scope. Try passing the Jquery object into the activateNav method, then your "this" reference in your prototype method should be fine. – xDaevax Jul 23 '14 at 18:30
  • Sorry, but what do you mean by "passing jQuery object into activateNav method"? – Daniel Ortiz Jul 23 '14 at 18:43
  • See if this helps: http://jsfiddle.net/xDaevax/ZUkjs/ – xDaevax Jul 23 '14 at 18:51

1 Answers1

2

Just save a reference to this and use it later.

slider.prototype.activateNav = function () {
    var that = this;
    this.nav.on('click', function (e) {        
        that.setCurrent($(this).data('dir'));
        e.preventDefault();
    });
};
Scimonster
  • 32,893
  • 9
  • 77
  • 89