Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9085159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T21:10:39+00:00 2026-06-16T21:10:39+00:00

Possible Duplicate: Javascript closure inside loops – simple practical example Recently I have been

  • 0

Possible Duplicate:
Javascript closure inside loops – simple practical example

Recently I have been playing around with some of the more complicated aspects of JavaScript, one of which is design patterns and delegation.

I have created a object containing 2 keys, which I then parse and attach an event onto the body.

My problem is that it seems like the last function is attached for any iteration of the for loop. I am pretty sure this is a copy by reference/scoping(thanks Shmiddty) problem, but please correct me if I am wrong.

Is there anyway to fix my issue to attach the 2 events on properly without changing too much? (As this is a complex app that I have simplified down to the issue at hand).

On the jsfiddle example please see how the alert message for .div1 is the same as .div2

var foo = {
    init: function() {

        var i = 0,
            keys = []
            self = this;

        for (var key in this) {
            keys.push(key);
        }

        for (i; i < keys.length; i++) {
            if (keys[i].match(/^on/i)) {
                var delegateFunc = keys[i].split(' | '),
                    event = delegateFunc[2],
                    selector = delegateFunc[1],
                    keyName = keys[i];

                console.log('###');
                console.log( 'selector: ' + selector );
                console.log( 'event: ' + event );
                console.log( 'function: ' + self[keyName] );

                $('body').on(event, selector, function(ev) {
                    self[keyName](ev, ev.target);
                });
            }
        }

    },

    'on | .div1 | click': function(ev, el) {
        alert('you clicked 1');
    },

    'on | .div2 | click': function(ev, el) {
        alert('you clicked 2');
    }
}

$(function() { foo.init(); });​

Any more info needed? Leave me a comment. Cheers

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T21:10:41+00:00Added an answer on June 16, 2026 at 9:10 pm
                $('body').on(event, selector, function(ev) {
                    self[keyName](ev, ev.target);
                });
    

    replace this with the following code:

                (function(keyName) {
                    $('body').on(event, selector, function(ev) {
                        self[keyName](ev, ev.target);
                    });
                })(keyName);
    

    The reason for this is that JavaScript doesn’t have a block scope. So your var keyName is the same variable in each loop and the closure of your callback function binds the variable, not the value it has at that moment. So as soon as the loop finished the variable will be whatever its last value was in all your callback functions.

    By adding the immediately-executed function which takes keyName as an argument you create a new variable (the function argument) and thus avoid the issue.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Javascript closure inside loops - simple practical example I'm playing around with
Possible Duplicate: Javascript closure inside loops - simple practical example I have an array
Possible Duplicate: Javascript closure inside loops - simple practical example I'm having a problem
Possible Duplicate: Javascript closure inside loops - simple practical example I am trying to
Possible Duplicate: Javascript closure inside loops - simple practical example Please explain the use
Possible Duplicate: Javascript closure inside loops - simple practical example javascript variable scope/closure in
Possible Duplicate: Javascript closure inside loops - simple practical example I was trying to
Possible Duplicate: Javascript closure inside loops - simple practical example I add event handlers
Possible Duplicate: Javascript closure inside loops - simple practical example I'm creating a table
Possible Duplicate: Javascript closure inside loops - simple practical example Calling setTimeout function within

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.