1

I am creating a system where content is loaded dynamically from a JSON file. The JSON file describes the content which is created by jQuery. I am trying to add events dynamically. It is working, but if I try to add events to two or more new dom elements, they all get whatever the last event was added. I guess I am doing something wrong with referencing to my new dom events, but can't figure out what...

A partial example of JSON content would be:

{
  "container" : {
    "id" : "container",
    "dom_type" : "<div>",
    "attr" : {
      "class" : "container",
      "id" : "container"
    },
    "children" : {
      "input_submit" : {
         "dom_type" : "<button>",
         "html" : "Submit",
         "attr" : {
            "type" : "submit",
            "id" : "submit",
            "class" : "submit"
            },
         "event": {
            "type": "submit",
            "name": "submitevent"
            }
          },
        "input_cancel" : {
         "dom_type" : "<button>",
         "html" : "Cancel",
         "attr" : {
            "type" : "submit",
            "id" : "cancel",
            "class" : "submit"
            },
         "event": {
            "type": "submit",
            "name": "cancelevent"
            }
          }
        }
      }

Now, my function reads the JSON file, jquery makes it an object and with a series of if/then statements, I create some dom and insert it:

// here, json is a JavaScript object made by jQuery with getJson..
function makeDom (json, dom_container) {
     for (var child in json.children)
        {
            var tp = json.children[child];

            // make dom element and add id (id is required)
            if (!tp['attr'])
            {
                
                $.error('jquery.myplugin.loadscreen() - erreur: Required child object "attr" not found in ' + child + '.')
            }

            if (undefined == tp['attr']['id'])
            {
                
                $.error('jquery.myplugin.loadscreen() - erreur: Required parameter "id" not found in "attr" in ' + child + '.');
            }

// ---------------------------------------------------------------
// I guess there is something wrong with this 'el' variable, because
// when I add the event to it, all similar elements get the event
// ----------------------------------------------------------------
    //add ID
            var el = $(tp['dom_type']);
            el.attr('id', tp['attr']['id']);
            
            // add type if any
            if (tp['attr']['type']) {
                el.attr('type', tp['attr']['type'])
            }

            // add for  if any
            if (tp['attr']['for']) {
                el.attr('for', tp['attr']['for'])
            };
            
    // add class if any
    if (tp['attr']['class']) {
        el.addClass(tp['attr']['class']);
    }
                
            // add src if any
            if (tp['attr']['src']) {
                el.attr('src', tp['attr']['src'])
            };

            // add href if any
            if (tp['attr']['href']) {
                el.attr('href', tp['attr']['href'])
            };

            // add html if any
            if (tp['html']) {
                el.html(tp['html']);
            };
            
       // add value if any
    if (tp['attr']['value']) {
        el.attr('value', tp['attr']['value']);
    };
            
            // add event if any
            if (tp['event']) {
                el.bind(tp['event']['type'], function(e){
                    //do something;
             });    
    dom_container.append(el);           
}

then, what happens is that both buttons get the "cancel" event, as it was the last added... How can I get this 'el' variable to point the the right DOM element?

1 Answer 1

3

The el variable is shared by all of the event handlers in a single closure.

You need to make a separate method that attaches the event handler and takes the variables as parameters.
Each call to the function will create a separate closure for the event handler, with a separate copy of the variable.

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

3 Comments

Should I make another method to attach the event handler and pass it 'el' and the other variables? as in if(tp['event']) { newMethod(el,eventType); } ?
@Regis: Yes. You can just move the entire body of the loop into the function that takes child, json, and dom_container as parameters.
Just a follow up: I did try it and it does work perfectly. Obviously, now that I have read more about closure, it makes more sense. Thanks again SLaks!

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.