function EntityCollection(element) {
this.$element = $(element);
this.$itemsContainer = this.$element.find('.js-entity-collection-items');
this.prototypeName = this.$element.data('prototype-name') || '__name__';
this.prototypeHtml = this.$element.data('prototype') || null;
this.itemClass = this.$element.data('item-class') || 'entity-collection__item';
this.index = this.$itemsContainer.find('.' + this.itemClass).length || this.$itemsContainer.children().length;
this.init();
}
EntityCollection.prototype.init = function() {
var self = this;
this.$element.on('click', '.js-entity-collection-add', function() {
self.addItem();
});
// Поддерживаем разные селекторы кнопки удаления (в шаблонах мог использоваться старый класс)
this.$element.on('click', '.js-entity-collection-remove', function() {
var $item = $(this).closest('.' + self.itemClass);
if ($item.length) {
$item.remove();
}
});
};
EntityCollection.prototype.addItem = function() {
if (!this.prototypeHtml) {
console.warn('EntityCollection: prototypeHtml is missing');
return;
}
var newForm = this.prototypeHtml.replace(new RegExp(this.prototypeName, 'g'), this.index);
var $wrapper = $("<div></div>").addClass(this.itemClass + ' mb-3 p-3 border rounded');
$wrapper.html(newForm + "<div><button type=\"button\" class=\"btn btn-sm btn-danger mt-2 js-entity-collection-remove\">Удалить</button></div>");
this.$itemsContainer.append($wrapper);
this.index++;
};