3

I'm building an image slider and I am running into some issues with event handlers and scope.

Simple HTML setup like so:

<section>
  <div class="container">
    <div class="closer-look-slider">
        <ul>
            <li class="one"></li>
            <li class="two"></li>
            <li class="three"></li>
            <li class="four"></li>
        </ul>
    </div>
    <div class="clear"></div>
    <div id="closer-look-slider-nav">
        <button data-dir="left">left</button>
        <button data-dir="right">right</button>
    </div>
  </div>
  <div class="clear"></div>
  <div id="closer-look-slider-thumbs">
    <a href="javascript:void(0);" class="active">1</a>
    <a href="javascript:void(0);">2</a>
    <a href="javascript:void(0);">3</a>
    <a href="javascript:void(0);">4</a>
  </div>

</section>

In my code I have got event handlers to check when the navigation buttons are clicked and upon doing so it'll fire the relevant functions. This all works fine if I have one slider but as soon as I add another slider to the page it start's getting confused.

Here's the code for the click events:

slider.prototype.trigger_events = function () {
    _self = this;

    this.nav.on('click', function () {
        _self.set_slide_pos(jQuery(this).data('dir'));
        _self.transition();
        console.log(_self.nav);
    });

    this.thumbs_elem.on('click', function () {
        _self.pagination_index(jQuery(this));
        console.log(_self.thumbs_elem);
    });
};

If for example I have two sliders on the page (exact same markup) then both sets of buttons control the second slider rather than the one corresponding to the button being clicked.

I've played around a little bit and my guess is that it's something to do with the scope? here's what I get when I do some console logging.

slider.prototype.trigger_events = function () {
    console.log(this.nav) // returns both navigation items

    this.nav.on('click', function () {
      console.log(_self.nav) // always returns the second nav and not the one that was clicked
    });
};

Obviously this is causing me problems as regardless of whichever nav I click, it always controls the second one.

2
  • 1
    Your _self is implicitly global! Commented Jul 23, 2014 at 13:40
  • 1
    _self = this; => var _self = this; Commented Jul 23, 2014 at 13:40

1 Answer 1

3

Your _self variable is implicitly global! Make it local to each trigger_events call by prefixing it with var (yes, it's a scope issue).

Sign up to request clarification or add additional context in comments.

1 Comment

so simple! Thanks for your help, as soon it lets me I'll accept your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.