Skip to content

Instantly share code, notes, and snippets.

@CraigChilds94
Created May 12, 2017 09:51
Show Gist options
  • Save CraigChilds94/50f784631cfbfc193e9810cf2038b058 to your computer and use it in GitHub Desktop.
Save CraigChilds94/50f784631cfbfc193e9810cf2038b058 to your computer and use it in GitHub Desktop.
Row/Block duplicator prototype.
/**
* Duplicate a row by the click of an
* element. Pass a callback to grab the new
* row and handle it how you please.
*
* @param {string} selector
* @param {Function} callback
*/
function Duplicator(selector, callback) {
this.selector = selector;
this.callback = callback;
this.bindEvents();
}
/**
* Bind the events to the element.
*
* @return {void}
*/
Duplicator.prototype.bindEvents = function() {
var self = this;
// Grab the latest elements to bind events to.
self.element = $(self.selector);
// Force unbind of any click events, re-bind a new
// click event on the element.
self.element.unbind('click').bind('click', function(e) {
e.preventDefault();
// Assume the row is the parent.
var row = self.element.parent();
// Create our new row and add it after.
var newRow = row.clone().insertAfter(row);
// Call our callback so we can
// sort out the new row.
self.callback(newRow);
// We don't need this button anymore?
self.element.remove();
// Rebind duplicator events.
self.bindEvents();
});
};
// Example markup
<div class="row">
<p>Stuff</p>
<a href="#" class="duplicator">New Row</a>
</div>
// Example JS
new Duplicator('.duplicator', function(newRow) {
newRow.find('p').html('Look I am a new row');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment