jQuery.ui.widget memory leak
inherit sample
by Yoshiharu Kamata
HTML
<script src="http://jqueryui.com/ui/jquery.ui.core.js"></script>
<script src="http://jqueryui.com/ui/jquery.ui.widget.js"></script>
<div id="container">loading...</div>
<div id="console"></div>
JavaScript
// jquery.ui.widget workaround
(function($,undefined){
// jquery.ui.widget
$.Widget.prototype._createWidget = function( options, element ) {
// $.widget.bridge stores the plugin instance, but we do it anyway
// so that it's stored even before the _create function runs
$.data( element, this.widgetName, this );
this.element = $( element );
this.options = $.extend( true, {},
this.options,
this._getCreateOptions(),
options );
var self = this;
// <--- memory leak
//this.element.bind( "remove." + this.widgetName, function() {
// self.destroy();
//});
// <--- workaround -- start
$.data( element, "widgetName", this.widgetName);
this.element.bind( "remove." + this.widgetName, this._destroy);
// <--- workaround -- end
this._create();
this._trigger( "create" );
this._init();
};
// new _destroy method
$.Widget.prototype._destroy = function(){
var widgetName = $(this).data("widgetName"),
self = $(this).data(widgetName);
self.destroy();
self.removeData("widgetName");
}
})(jQuery);
// test code
(function($,undefined){
var count = 0;
$.widget("ui.dummyParent",{});
$.widget("ui.dummy",$.ui.dummyParent,{
destroy: function(){
$("#console").text("call destroy:"+count++);
$.Widget.prototype.destroy.call( this );
}
});
})(jQuery);
setInterval(function(){
$("#container")
.empty()
.append("<div class='dummy'>dummy</div>")
.find(".dummy")
.dummy()
.end();
},1000);