Skip to content

Instantly share code, notes, and snippets.

@coma
Created May 30, 2012 09:19
Show Gist options
  • Save coma/2834947 to your computer and use it in GitHub Desktop.
Save coma/2834947 to your computer and use it in GitHub Desktop.
Probando...
(function($){
$.fn.comaCollection = function(){
var args = Array.prototype.slice.call(arguments);
if(args.length > 0 && typeof(args[0]) == 'string') {
var api = $(this).data('comaCollection');
var method = args.shift();
return api[method](args);
} else {
this.each(function(){
var collection = $(this);
var items = collection.find('tbody');
var actions = collection.find('div.actions');
var adder = actions.find('a.add');
var remover = actions.find('a.remove');
var proto = collection.find('script[type="text/html"]').text();
var count = (new Date()).getTime();
items
.find('td>a.remove')
.live('click', remove);
adder.click(add);
remover.click(removeAll);
check();
function remove(event) {
event.preventDefault();
$(this)
.parentsUntil('tr')
.parent()
.remove();
check();
}
function removeAll(event) {
event.preventDefault();
items.empty();
check();
}
function addRow(data) {
var id = '@' + count++;
var row = $(proto.replace(/\$\$name\$\$/g, id));
$.each(data, function(i) {
row.find('[name$="[' + i + ']"]').val(this);
});
return row.appendTo(items);
}
function add(event) {
event.preventDefault();
addRow([])
.find('[name]:visible')
.first()
.focus();
check();
}
function check() {
if(items.children().length > 0) {
actions.addClass('margen');
remover.show();
} else {
actions.removeClass('margen');
remover.hide();
}
}
var api = {
set: function(args) {
items.empty();
$.each(args[0], function(i) {
addRow(this);
});
check();
return items;
},
add: function(args) {
return addRow(args[0]);
}
}
collection.data('comaCollection', api);
});
return this;
}
}
})(jQuery);
$(function() {
$('.collection').comaCollection();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment