form.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. const Mn = require('backbone.marionette');
  2. const App = require('../../main');
  3. const AccessListModel = require('../../../models/access-list');
  4. const template = require('./form.ejs');
  5. const ItemView = require('./form/item');
  6. require('jquery-serializejson');
  7. const ItemsView = Mn.CollectionView.extend({
  8. childView: ItemView
  9. });
  10. module.exports = Mn.View.extend({
  11. template: template,
  12. className: 'modal-dialog',
  13. ui: {
  14. items_region: '.items',
  15. form: 'form',
  16. buttons: '.modal-footer button',
  17. cancel: 'button.cancel',
  18. save: 'button.save'
  19. },
  20. regions: {
  21. items_region: '@ui.items_region'
  22. },
  23. events: {
  24. 'click @ui.save': function (e) {
  25. e.preventDefault();
  26. if (!this.ui.form[0].checkValidity()) {
  27. $('<input type="submit">').hide().appendTo(this.ui.form).click().remove();
  28. return;
  29. }
  30. let view = this;
  31. let form_data = this.ui.form.serializeJSON();
  32. let items_data = [];
  33. form_data.username.map(function (val, idx) {
  34. if (val.trim().length) {
  35. items_data.push({
  36. username: val.trim(),
  37. password: form_data.password[idx]
  38. });
  39. }
  40. });
  41. if (!items_data.length) {
  42. alert('You must specify at least 1 Username and Password combination');
  43. return;
  44. }
  45. let data = {
  46. name: form_data.name,
  47. items: items_data
  48. };
  49. let method = App.Api.Nginx.AccessLists.create;
  50. let is_new = true;
  51. if (this.model.get('id')) {
  52. // edit
  53. is_new = false;
  54. method = App.Api.Nginx.AccessLists.update;
  55. data.id = this.model.get('id');
  56. }
  57. this.ui.buttons.prop('disabled', true).addClass('btn-disabled');
  58. method(data)
  59. .then(result => {
  60. view.model.set(result);
  61. App.UI.closeModal(function () {
  62. if (is_new) {
  63. App.Controller.showNginxAccess();
  64. }
  65. });
  66. })
  67. .catch(err => {
  68. alert(err.message);
  69. this.ui.buttons.prop('disabled', false).removeClass('btn-disabled');
  70. });
  71. }
  72. },
  73. onRender: function () {
  74. let items = this.model.get('items');
  75. // Add empty items to the end of the list. This is cheating but hey I don't have the time to do it right
  76. let items_to_add = 5 - items.length;
  77. if (items_to_add) {
  78. for (let i = 0; i < items_to_add; i++) {
  79. items.push({});
  80. }
  81. }
  82. this.showChildView('items_region', new ItemsView({
  83. collection: new Backbone.Collection(items)
  84. }));
  85. },
  86. initialize: function (options) {
  87. if (typeof options.model === 'undefined' || !options.model) {
  88. this.model = new AccessListModel.Model();
  89. }
  90. }
  91. });