简体   繁体   中英

Event handler binding memory leaks

I have the following html:

<table id="link-table" class="style-1" style="width: 100%;">
    <thead><tr><th>&nbsp;</th><th>Name <small>(75 characters)</small></th><th>Link</th><th></th></tr></thead>
    <tbody id="link-table-body"></tbody>
</table>

The body of this table is generated from a jsRender template:

<script id="tmpl-edit-mylinks-list" type="text/x-jsrender">
  {{for links}}
    <tr>
        <td style="width: 1%;"><a href="#" class="move-up ir sprites-arrow-up-sm">Up</a><a href="#" class="move-down ir sprites-arrow-down-sm">Down</a></td>
        <td style="width: 1%;"><input type="hidden" id="hdnLinkId" value="{{attr:LinkID}}" /><input id="txtLinkText" type="text" class="text" value="{{attr: LinkTitle}}" /></td>
        <td><input id="txtLinkUrl" type="text" class="text" style="width: 100%;" placeholder="http://" value="{{url:URL}}" /></td>
        <td><img src="/resources/images/sprites/cancel-black.png" class="delete-person-link" data-linkid="{{attr:LinkID}}" style="cursor:pointer;" /></td>
    </tr>
  {{/for}}
</script>

The template is applied with the result of an ajax call:

success: function (data) {
            var links = { links: data };

            var templateHtml = $("#tmpl-edit-mylinks-list").render(links);

            $('#link-table-body').html(templateHtml);


            //Attach handlers
            $('.move-up').click(function (e) {
                moveUpClicked(this);
            });

            $('.move-down').click(function (e) {
                moveDownClicked(this);
            });

            $('.delete-person-link').click(function (e) {
                DeletePersonLink(this);
            });
        }

I was unable to get these .click handlers to bind using Jquery's .on().

My question is, will binding the handlers like this cause a memory leak?

Should I be calling unbind() before replacing the html and attaching a new handler?

Jquery html() method call internally empty() method which is using cleanData() . Using your actual code, you wouldn't have any memory leaks. That's said, you could avoid binding multiple duplicate handlers for many elements by delegating this event, eg using:

$('#link-table-body').on('click', '.move-up' , moveUpClicked);

FYI, this is part of jQuery lib:

empty: function() {
        var elem,
            i = 0;

        for ( ; (elem = this[i]) != null; i++ ) {
            // Remove element nodes and prevent memory leaks
            if ( elem.nodeType === 1 ) {
                jQuery.cleanData( getAll( elem, false ) );
            }

and part of html() method:

if ( elem ) {
                this.empty().append( value );
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM