I created a plugin that clones elements for rapid prototyping. The plugin will iterate through each element that has a data-attribute of ‘data-clone’ on the element, and clone amount set in the attribute.
example:
<table data-clone="3">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Project</th>
</tr>
</thead>
<tbody>
<tr data-clone="4">
<td>1</td>
<td>Steve Sax</td>
<td>Something here.</td>
</tr>
</tbody>
</table>
This seems to work well on the first element. However, if i have a nested item where the container is cloned and so are elements inside. It seems it clones the nested items, and the outer on the first, but will not clone those nested items into the newly cloned outer containers.
I have a fiddle here: Fiddle
It has the plugin and the call. If you click ‘Run’ you should see exactly what I mean.
However, I feel if the .each() method iterated from the nested item first, then worked its way up, all clones would be correct.
Thanks in advance,
Adam.
Here is the plugin itself for reference. Again, all is in the fiddle as well.
/*! Adamin Clone - v0.1.0 - 2012-09-29
* https://github.com/pensive612/Adamin-Clone
* Copyright (c) 2012 Adam L.; Licensed MIT, GPL */
(function(window, document, $, undefined) {
var Project = function(elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('clone-cap');
};
Project.prototype = {
defaults: {
cloneCap: 100
},
init: function() {
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.getCloneValue(this.$elem);
return this;
},
getCloneValue: function(elem) {
var configCap = this.config.cloneCap;
var cloneValue = elem.data('clone');
// parse data-clone value
cloneValue = this.parseCloneValue(cloneValue);
// if data-clone value is valid, send to clone function
if ( cloneValue && (cloneValue < configCap) ) {
this.cloneItem(this.$elem, cloneValue);
// otherwise, return false
} else {
if (cloneValue > configCap) {
window.console.log('Your data-clone value is too high for the defaults. Please check documentation to override cap in config.');
}
return false;
}
},
parseCloneValue: function(value) {
var cloneValue = parseInt(value, 10);
return cloneValue;
},
cloneItem: function(elem, value) {
var elemClone;
for (var i = value; i > 0; i--) {
elemClone = elem.clone(true);
elemClone.removeAttr('data-clone');
elemClone.addClass('clone-' + i);
elemClone.insertAfter(elem);
}
}
};
Project.defaults = Project.prototype.defaults;
$.fn.adaminClone = function(options, callback) {
if (typeof callback === 'function') {
callback.call(this);
}
return this.each(function() {
new Project(this, options).init();
});
};
window.Project = Project;
}(window, document, jQuery));
ComputerArts did an awesome job of rewriting the function. However, I was able to maintain the plugin pattern and extendibility by only modifying:
To this:
Using parents().length is a great way to measure depth. Thanks to ComputerArts and Shoky for getting me where I needed to be on it.