Bucky
Bucky

Reputation: 929

Why can I not reference my jQuery object inside a callback?

I store a jquery object (a collection of html elements) but when I come to reference the object in another function it comes back as 'undefined'! Here's my code:

this.container = $('#slide-menu'), // The menu container (e.g. a UL)
this.items = this.container.find('.menu-item'); // The menu items (e.g. all li's)
this.links = this.items.find('.link'); // The menu links

this.getCurrent(); // Set the current menu-item
this.getPrev(); // Set the previous menu-item
this.getNext(); // Set the next menu-item

console.log(this.items); // !!! The items exist here !!!

// Setup the menu items click events:
this.items.bind('click', function(e) {

    console.log(this.items); // !!! But not here !!! ???

    e.preventDefault();
    o = $(e.currentTarget); // Set jquery object

    if (!o.hasClass('active')) { // Prevent action on current menu-item
        this.items.find('.active').removeClass('active'); // Remove the current active menu-item
        o.addClass('active'); // Set new active menu item

Does anyone have any idea why this is happening because it's driving me crazy and as far as I can see this should not be possible. Is javascript is broken?! Hmmm, what do you think?

Upvotes: 1

Views: 105

Answers (2)

Richard Dalton
Richard Dalton

Reputation: 35803

It's a scope problem.

this outside of your click event handler is not the same as this inside the handler. Inside the handler it refers to the element being clicked. Outside it is likely the global window object.

This should work fine:

var items = this.container.find('.menu-item');

items.bind('click', function(e) {
     console.log(items); 

Don't use this in JavaScript unless you actually need to.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

When is an jquery object not an object?

Never.

When it's undefined!

Or when it's not where you think it is.

Does anyone have any idea why this is happening because it's driving me crazy and as far as I can see this should not be possible. Is javascript is broken?! Hmmm, what do you think?

No, Javascript is not "broken".

You've assumed this.items always refers to the same thing. It does not. Inside your bind, this is the thing that was clicked on, rather than whatever it is outside of that callback function.

Inside your callback, you ought to write $('#slide-menu').find('menu-item') rather than this.items.

Upvotes: 4

Related Questions