enb081
enb081

Reputation: 4061

Calling a function from within itself

I have several elements inside a container. All their events are handled inside a function events().

On click of a button inside the container, I replace the container's html with the response from an AJAX request.

function events() {
    $(".btn").on("click", function() {
     ...
    }); 

    $(".txt").on("keyup", function() {
     ...
    });

    $(".btn2").on("click", function() {
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4) {
                       $(".container").html(xmlhttp.responseText); 
                       events(); // ***
                    }
                }
                url = 'handlers/gethtml.ashx';
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
        });
}

Now, I need to rebind all the controls with events so after changing the html $(".container").html(xmlhttp.responseText); I call the function within itself because the new html contains the same controls with the same events.

Does this cause stack overflow? I have some performance issues so i was wondering if this maybe the cause. Also, is there any workaround, maybe a more elegant way to do this?

Upvotes: 1

Views: 211

Answers (3)

Sébastien Renauld
Sébastien Renauld

Reputation: 19672

Just call events(). It is in the scope!

There are a couple of things you need to be aware of, though:

  1. Elements already on there will have two click handlers on the second run - the old, and the new. To get rid of them, use unbind to unbind all click events, for example.
  2. You may want to split up your event creation function further.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try using event delegation, you don't need to bind the event again

$(".container").on("click",".btn2", function() {...});

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388446

Use event delegation, then no need to rebind the events since it will handle dynamic element as well

You could further shorten the code by using jquery to load the url contents

function events() {
    var ct = $(".container");
    ct.on("click", ".btn", function() {
    }); 

    ct.on("keyup", ".txt", function() {
    });

    ct.on("click", ".btn2", function() {
        ct.load('handlers/gethtml.ashx')
    }

Upvotes: 2

Related Questions