在自定义UI小部件上调用jQuery .remove()会导致无限循环 [英] calling jQuery .remove() on custom UI widget causes infinite loop

查看:106
本文介绍了在自定义UI小部件上调用jQuery .remove()会导致无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为uiPopover的自定义jQuery UI小部件,与UI对话框非常相似(实际上,大多数代码是从其中复制粘贴的).该窗口小部件具有一个自定义的destroy方法,该方法隐藏该窗口小部件并将其从DOM中删除.同样,这几乎是UI对话框中的复制粘贴.

I have created custom jQuery UI widget called uiPopover, very similar to UI-dialog (in fact, most of the code is copy-paste from it). This widget has a custom destroy method that hides the widget and removes it from the DOM. Again, it's pretty much copy-paste from UI-dialog.

    destroy: function() {
        var self = this;

        if (self.overlay) {
            self.overlay.destroy();
        }
        self.close();
        self.element
            .removeData('popover');
        self.uiPopover.remove();
        console.log('afterRemove')

        return self;
    },

奇怪的是,这会导致引发一些错误的无限循环:

The weird thing is that this causes an infinite loop that throws some errors:

$('#element').popover();
$('#element').remove();

据我所见,问题是当我调用.remove()时,它会自动在我的小部件(这是jQuery UI中内置的)上调用destroy(),并且destroy方法尝试调用remove() )再次放在我的元素上,然后尝试再次调用destroy(),依此类推.

As far as I can see, the problem is that when I call .remove(), it automatically calls destroy() on my widget (this is built-in in jQuery UI) and the destroy methodd tries to call remove() again on my element, and then that tries to call destroy() again and so on..

但是,奇怪的是,这在UI对话框中不会发生.所以当我这样做时:

However, the weird thing is that this doesn't happen with UI dialog. So when I do this:

$('#element').dialog();
$('#element').remove();

一切都很好...我的插件肯定有问题,但是我不知道是什么.

Everything is okay... There must be something wrong with my plugin, but I cannot figure out what.

以下是我的插件的完整资料: https://gist.github.com/2208569

Here is the full source of my plugin: https://gist.github.com/2208569

推荐答案

除了对jQuery UI本身进行修改以外,对destroy()的递归调用没有什么可做的.但是,可以通过阻止再次调用remove()来断开链条:

There's not much you can do about the recursive call to destroy(), aside from modifying jQuery UI itself. You can, however, break the chain by preventing remove() from being called again:

destroy: function() {
    var self = this;

    if (self.overlay) {
        self.overlay.destroy();
    }
    self.close();

    if (self.element.data("popover")) {
        self.element.removeData("popover");
        self.uiPopover.remove();
    }

    return self;
}

请注意,您不必复制和粘贴代码即可扩展现有的小部件,因为小部件框架

Note in passing that you don't have to copy and paste code in order to augment existing widgets, as the widget framework supports prototype inheritance. It would be interesting to know if your problem still occurs if you have your widget derive from $.ui.dialog instead of duplicating its code base.

这篇关于在自定义UI小部件上调用jQuery .remove()会导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆