Reputation: 4061
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
Reputation: 19672
Just call events()
. It is in the scope!
There are a couple of things you need to be aware of, though:
unbind
to unbind all click
events, for example.Upvotes: 1
Reputation: 44740
Try using event delegation, you don't need to bind the event again
$(".container").on("click",".btn2", function() {...});
Upvotes: 2
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