recently I have been studying way of refactoring Jquery code to handling UI events.
Jquery is on the down hill due to invention of MVVM frame works and library such as angler, vue, react therefore It was hard to find documents which wrote recently.
So, I write my result via this document and hope reviewing my decision from skilled developers such as you.
<purpose of refactoring>
- separate codes by functionality
- improve readability
Jquery source is composed by html elements’ event. So I usually saw coding style below
$("#nameText").on("input", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#surveyText").on("input", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#submitBtn").on("click", function (e) {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
It’s pretty simple and we can read which action is needed and conducted by some elements action.
But that could be verbose and confusing us because there are many roles and we have to check the element’s css attributes which related selector.
Some times, css class name or id don’t have proper name which not enough explain role of element or in case of, use navigator function like find() or selector by element hierarchy.
$("#s_f01").find("li").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$(".s_btn01").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#submitBtn").on("click", function (e) {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
And functions for particular element could be spread out by modified history for adding function or some of modification.
//Codes for Survey Form (line 10 - 200)
$("#s_f01").find("li").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$(".s_btn01").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#submitBtn").on("click", function (e) {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
,,,
//added after statistics function for enable Survey form action(line 1200)
$("#SurveyFormOpenBtn").on("click", sendStatisticInfo_SurveyFormOpened());