模块化JS:3个部分的全局function(复选框和无线电)和Sholud我在我的代码中应用“渲染”?

这是我的网络应用程序中的一个部分,用户可以“订阅”在3个不同时间发送的报告:每周,每月,每季度。 (可以从三者中选择1个选项)。

我在努力解决这个问题时,我正在努力规划最佳解决方案。

应该怎么做:

  • 加载页面时,我必须传递一个PHP var,它将设置用户报告的当前状态(变量report在我的代码[{weekly},{Monthly},{Quarterly}]的乞讨中)0,1,2 ,3将是指标。 例如:如果用户过去设置了他想要每月6个月的报告 – 他将会看到“每月”选中复选框 – 并且在单选按钮中选择“6个月”,变量将设置为[0,2,0]

  • 选择复选框时 – 可以选择3(或一个)单选按钮。

  • 取消选中复选框时,将禁用单选​​按钮并删除所有检查。

  • “保存计划”按钮将数据发送到PHP。

我的问题是:

  1. 如何以模块化方式构建代码,防止意大利面条代码?

  2. 解决问题1后 – 我应该应用“渲染”function吗? (受此video教程的启发)

刚提到:

  • 这是一个JSFIDDLE,我的代码少了意大利面条。 – 包括目前正在运作的内容。

  • 我正在练习模块化JS代码,所以我很乐意获得有关我的代码的一般提示(推荐的链接,video和教程等)。

  • 我使用的是jQuery 1.3.2,它不包含当前库的所有function。 (像parents一样on.('click', func..)

HTML:

 Set Schedule 
Save Schedule

JS:

  /******************/ /** Set Schedule **/ /******************/ (function() { var schedule = { report: [], template: $('#report_schedule').html(), // Init functions init: function() { this.cacheDom(); this.bindEvents(); }, // Cache elements from DOM cacheDom: function() { this.$setScheduleBtn = $('#setScheduleBtn'); this.$reportSchedule = $('#reportSchedule'); this.$allFieldsets = this.$reportSchedule.find('fieldset'); this.$radioBtns = this.$allFieldsets.find('input[type="radio"]'); this.$saveBtn = $('#saveSchedule'); }, // Set events bindEvents: function() { var that = this; // Show/Hide "Set report" section this.$setScheduleBtn.click(this.showReportScheduler.bind(this)); // Checkbox-radio buttons clicks this.$allFieldsets.each(function() { let fieldset = this; $(this).find('input[type=checkbox]').change(function () { that.toggleRadioButtons(fieldset); }); }); // Update current report this.$radioBtns.change(this.updateReport.bind(this)); // Save button apply changes this.$saveBtn.click(this.saveSchedule.bind(this)); }, // Display on click showReportScheduler: function() { this.$reportSchedule.slideToggle("fast"); }, // Toggle Radio Buttons toggleRadioButtons: function(fs) { var radios = $(fs).find("input[type=radio]"); radios.attr("disabled", !radios.attr("disabled")); radios.removeAttr('checked'); }, updateReport: function(rd) { console.log(rd.get(0).parentNode); }, // Save data saveSchedule: function() { var selectedItems = []; this.$allFieldsets.each(function(){ var newylyChecked = $(this).find('input[type="radio"]:checked').val(); if ( newylyChecked == undefined ) newylyChecked = 0; selectedItems.push(parseInt(newylyChecked)); }); this.report = selectedItems; // console.log(this.report); if (this.sendReport(this.report)) { this.$reportSchedule.slideUp("fast"); } }, // Send report to server sendReport: function() { $.ajax({ type: "POST", url: '/potato/schedule_report.php', data: { weekly: this.report[0], monthly: this.report[1], quarterly: this.report[2], system_user_id:  }, success: function(data) { console.log(data); return true; } }); } }; schedule.init(); })();  

请随时询问更多信息或任何有助于我的帮助。

通过复选框或无线电btns进行任何更改时使用渲染: