Recreating buttonsets. Should I destroy before?
I am using jQuery UI (1.8.16) extensively in my application.
I've developed a simple function which fetches some json data with an ajax call and converts a DIV in a pager using jQuery UI buttonsets:
<div id="answersPager"></div>
this is the javascript:
BuildAnswersPager: function(selectedPage, totalPages) {
$("#answersPager").empty();
if (totalPages > 1) {
var ctl = [];
var isChecked = "";
for (var i = 1; i <= totalPages; i++) {
if (i === selectedPage) {
isChecked = " checked='checked'";
}
else {
isChecked = "";
}
ctl[i] = "<input class='answersRadioPager' type='radio' value='" + i + "' id='a_page_" + i + "' name='answer_pager' " + isChecked + "/><label for='a_page_" + i + "'>" + i + "</label>";
}
$("#answersPager").append(ctl.join(''));
$("#answersPager").buttonset();
}
}
I've bound each button to a live click event so that every time a user searches for a new term, I reload the window, build a new pager and allow him/her to page the results.
$(".answersRadioPager").live('click', function() {
// Fetches json data (new page)
});
Everything works fine but I was wondering if I 开发者_如何学编程have to destroy the buttonset before I rebuild it (at the moment I just empty it).
Are there any memory issues I must be aware of ?
Not really. .empty
removes all data and handlers attached to any removed markup via jQuery's internal .cleanData
method thereby preventing any memory leaks, so you are quite safe. From the docs:
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
FYI - .html
also invokes .cleanData
, so using .html('')
is equivalent.
A buttonset(), even if never attached to a parent node, will not mark itself as ready for garbage collection.
Try:
- Take a heap snapshot.
- Instantiate n buttonsets, but don't attach to any parents, nor add any listeners.
- Take a heap snapshot.
- Compare the two snapshots and note the delta of HTMLButtons has increased.
I have found it requires calling buttonset('destroy') to remedy the situation.
精彩评论