Petter Thowsen
Petter Thowsen

Reputation: 1727

Javascript Weird - I'm clueless

I'm working on this menu-system that's very similar to how operating systems do them. Using jquery etc.

I have 2 comments down in the For Loop. It's basically outputting the last index each in the $(document).on('click')... function. But outside the document.on it works fine.

It's probably just an obvious problem but I've spent about an hour on this.. Thanks in advance!

    menu: function(title) {
        this.title = title;
        this.slug = slugify(title);
        this.icon = false;
        this.buttons = Object();
        this.num_buttons = 0;
        this.visible = false;
        this.timeout_id = null;
        this.is_hovering_dropdown = false;
        this.is_hovering_menu = false;


        this.render = function() {
            var that = this;
            var slug = that.slug;
            var str = '<li id="menu-' +slug +'"><a href="#" id="menu-toggle-' +slug + '">' + this.title + '</a>';

            if (this.num_buttons > 0) {
                str += '<ul id="menu-dropdown-' + slug + '" style="display: none;" class="dropdown">';
                for (var button in this.buttons) {

                    str += '<li><a href="#" id="menu-dropdown-' + slug + '-' +that.buttons[button]['slug'] +'">' +that.buttons[button]['title'] +'</a></li>'

                    alert(button) //new project, open project, save as etc.
                    $(document).on("click", "#menu-dropdown-" +slug + '-' + that.buttons[button]['slug'], function() {
                        $("#menu-dropdown-" + slug).hide("fade", 200);
                        that.visible = false;

                        alert(button);//save as, save as, save as, save as etc.
                    });
                }
            }
        }
    }

Upvotes: 0

Views: 66

Answers (1)

LetterEh
LetterEh

Reputation: 26706

Here you go:

Thanks to the order of operations, and scoping, all of your buttons are being saved with a reference to the LAST value of button.

What you want to do is put that assignment inside of an immediately-invoking function, and pass the button into that particular function-scope.

(function (button) { $(document). //...... }(button));

Everything inside of the immediate function should still have access to the static stuff outside of the immediate-function's scope (ie: that), AND it will also have a reference to the current value of button, as it's being invoked then and there.

The longer version of the story is that your buttons, when being created are being given a reference to button, rather than the value of button, therefore, when they're actually invoked at a later time, they reference the value of button as it currently exists (ie: the last value it was assigned in the loop).

Upvotes: 1

Related Questions