I am using the jquery plugin boilerplate (available here) to create an extension of the div element. The plugin is meant to add other divs or elements inside the original div. My problem is that I would like to be able to destroy and re-create the elements inside the div.
Here is a simplified example of the the plugin code:
(function($) {
$.extension = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {}
}
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
// code goes here
var newDiv = $(document.createElement("div"));
newDiv.html("hello world");
$element.append(newDiv);
}
plugin.foo_public_method = function() {
// code goes here
}
var foo_private_method = function() {
// code goes here
}
plugin.destroy = function () {
$element.empty();
}
plugin.init();
}
$.fn.extension = function(options) {
return this.each(function() {
if (undefined == $(this).data('extension')) {
var plugin = new $.extension(this, options);
$(this).data('extension', plugin);
}
});
}
})(jQuery);
As you can see I use the jquery empty() method to erase the children of the div. It erases fine but then I am not able to re-create them.
Here is the html code used to call the plugin:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jquery1.7.2.min.js"> </script>
<script type="text/javascript" src="js/extension.js"> </script>
</head>
<body>
<button type="button" id="destroy">Destroy</button>
<button type="button" id="create">Create</button>
<div id="random" ></div>
<script>
$('#random').extension();
$('#destroy').click(function(){
$('#random').data('extension').destroy();
});
$('#create').click(function(){
alert("hey");
$('#random').extension();
});
</script>
</body>
</html>
What am i doing wrong?
You are not removing the old data so the plugin isn’t recreated because it won’t be
== undefinedTry