qs.defineNS('app.user'); app.user.CommitteeSubForm = qs.createObject(); app.user.CommitteeSubForm.prototype = { initialize: function (options) { this.form = null; this.subForm = null; this.options = $.extend({ btnDeleteSelector: '.btn-delete', btnAddSelector: '.btn-add', renderAction: 'renderCommitteeRow' }, options); this.form = $('#' + this.options.formId); if (!this.form.length) { alert('Error: Form "' + this.options.formId + '" is not found.'); return; } this.subForm = $('#' + this.options.subFormId + '-element', this.form); if (!this.subForm.length) { alert('Error: SubForm "' + this.options.subFormId+ '" is not found.'); return; } if (!this.options.renderUrl) { alert('Error: Render URL is not defined.'); return; } this.initActions(); }, initActions: function () { this.initDeleteActions(); this.initAddAction(); }, initDeleteActions: function () { var elements = $(this.options.btnDeleteSelector, this.subForm); if (!elements.length) { alert('Error: "Delete" buttons are not found.'); return; } $(elements).unbind('click.committee'); $(elements).bind('click.committee', _.bind(this.deleteRow, this)); }, initAddAction: function () { var element = $('#' + this.options.subFormId + '-btnAddItem', this.subForm); if (!element.length) { alert('Error: "Add" button is not found.'); return; } $(element).unbind('click.committee'); $(element).bind('click.committee', _.bind(this.addRow, this)); }, deleteRow: function (ev) { var children = $(ev.currentTarget).closest("tbody").children(); if (2 > children.length) { var showAlert = true; $(children).find('input[type=text], select').each(function () { var value = $(this).val(); value = _.str.trim(value); if (value != '') { showAlert = false; } $(this).val(''); }); if (showAlert) { alert('Row is empty and can\'t be removed.'); } } else if (confirm('Do you really want to delete this Item?')) { $(ev.currentTarget).closest("tr").remove(); } }, addRow: function (ev) { var data = { action: this.options.renderAction, itemClass: this.options.itemClass, itemName: this.options.itemName, itemIndex: this.getNextRowIndex() }; qs.ajax(this.options.renderUrl, data).success($.proxy(this.addRowSuccess, this)); }, addRowSuccess: function (response) { if ('success' == response.status) { $('tbody', this.subForm).append(response.html); if (response.scripts) { $.globalEval(response.scripts); } this.initActions(); } else { alert('Error, new price option is not added.') } }, getNextRowIndex: function() { var index = 0; $('tbody tr', this.subForm).each(function (i, el) { var rowIndex = '' + $('input, select', el).filter(':first').prop('name'); rowIndex = rowIndex.replace(/[^0-9]+/g, ''); rowIndex = parseInt(rowIndex); if (isNaN(rowIndex)) { rowIndex = new Date().getTime(); } if (rowIndex > index) { index = rowIndex; } }); return ++index; } };