这个jQuery代码是否创建了循环引用?

时间:2012-01-18 22:46:45

标签: jquery

我对jQuery比较陌生,我正在努力自学。

虽然在下面的代码中不是特别重要,但在我的应用程序中,有许多部分会在任何时候触发大量事件,因此我关注循环引用和潜在的内存泄漏,同时仍然获得最大性能在变量中缓存对象的好处。

但是我似乎不太明白导致循环引用的原因,我当然不知道如何调整我的代码来防止它们。

以下代码是否会导致循环引用?如果是这样,怎么可以避免?

$('body').on('click', '#timestamped-comment-template', function(e){

    var $target = $(e.target),
        $this = $(this),
        songid = $this.data('songid'),
        array = [];

    if ($target.is('input.reply')) {

        var data = {
           'user-url'  :   $('#BP_loggedin_user_helper').text(),
            'avatar'    :   $('#LoginWithAjax_Avatar').find('img').attr('src'),
            'timestamp' :   $this.find('.time').find('h6').text(),
            'replyto'   :   $this.find('li').last().find('strong').find('a').find('h6').text()
        };

        array.push(data);   

        $this
            .addClass('commenting')
            .find('input')
                .hide()
            .end()
            .find('.replies')
                .after($.render(array, 'replyFormTemplate'))
            .end()  
            .on('click', '.cancel', function(){             
                $this
                    .removeClass('commenting')
                    .find('input')
                        .show()
                    .end()
                    .find('.timed-comment-form')
                        .remove()
                    .end()
                    .off('click', '.cancel');               
                adjustTemplateHeight(songid);               
            });         
        adjustTemplateHeight(songid);
    }   
});

// get template position

function adjustTemplateHeight(songid){

    var $self = $('#timestamped-comment-template'),
        barheight = Number($('#comment-bar-' + songid).offset().top),                               
        contentheight = Number($self.find('.content').actual('height')),
        newheight = barheight - contentheight;

        $self.css({top: (newheight-15) + 'px'})
             .find('.arrow')
                .css({top: contentheight + 'px'});  
}

关注我的部分是嵌套的匿名函数,因为我的理解是这是他们最常出现的地方:

.on('click', '.cancel', function(){             
           $this.removeClass('commenting')
                .find('input').show().end()
                     .find('.timed-comment-form')
                          .remove()
                              .end()
                                 .off('click', '.cancel');               
                                        adjustTemplateHeight(songid);               
      });         

0 个答案:

没有答案