const cuentas = { id: '#cuentas', cuentas: [], categorias: [], getCuentas: function() { return $.ajax({ url: _urls.api + '/cuentas', method: 'GET', dataType: 'json' }).then((data) => { if (data.cuentas === null || data.cuentas.length == 0) { return } this.cuentas = data.cuentas }).then(() => { this.draw() }) }, getCategorias: function() { return $.ajax({ url: _urls.api + '/categorias', method: 'GET', dataType: 'json' }).then((data) => { if (data.categorias === null || data.categorias.length == 0) { return } this.categorias = data.categorias }).then(() => { this.drawCategorias() }) }, drawCategorias: function() { const select = $("[name='categoria']") $.each(this.categorias, (i, el) => { select.append( $('').attr('value', el.id).html(el.nombre) ) }) }, buildParent: function(segment) { const table = $('
').attr('class', 'ui table').append( $('').append( $('').append( $('').html('Cuenta') ).append( $('').html('Categoría') ).append( $('').attr('class', 'right aligned').append( $('').attr('class', 'ui tiny green circular icon button').append( $('').attr('class', 'plus icon') ) ) ) ) ) table.find('.ui.button').click((e) => { e.preventDefault() this.add() return false }) parent = $('') table.append(parent) segment.append(table) return parent }, getParent: function() { const segment = $(this.id) let parent = segment.find('tbody') if (parent.length == 0) { parent = this.buildParent(segment) } return parent }, draw: function() { const parent = this.getParent() parent.html('') $.each(this.cuentas, (i, el) => { parent.append( $('').append( $('').html(el.nombre) ).append( $('').html(el.categoria.nombre) ) ) }) }, add: function() { this.modal.find('form').trigger('reset') this.modal.modal('show') }, doAdd: function() { const data = JSON.stringify({ categoria_id: $("[name='categoria']").val(), nombre: $("[name='nombre']").val() }) return $.ajax({ url: _urls.api + '/cuentas/add', method: 'POST', data: data, dataType: 'json' }).then((data) => { this.modal.modal('hide') this.getCuentas() }) }, setupModal: function() { this.modal = $('.ui.modal') this.modal.modal() this.modal.find('.close.icon').css('cursor', 'pointer').click(() => { this.modal.modal('hide') }) this.modal.find('form').submit((e) => { e.preventDefault() this.doAdd() return false }) }, setup: function() { this.setupModal() this.getCuentas().then(() => { this.getCategorias() }) } }