javascript - How to modularize jQuery? -
i trying modularize following code, there object functions declared globally , bad practice
$(document).ready(function() { $('#registrationform').on('submit', function(event) { var valid = checkvalidate(); if(!valid) { event.preventdefault(); } }); $('#termsaccepted').on('change', function() { if($(this).is(":checked")) { $('.error').hide(); } }); $('#otherpaymentid').hide(); $('#paymentid').on('change', showpaymentidbox); }); var showpaymentidbox = function() { var myradio = $('input[type=radio][name=paymentid]:checked').val(); if (myradio == 0) { $('#otherpaymentid').hide().val(''); } else { $('#otherpaymentid').show(); } } var checkvalidate = function() { var validity = true; if(!$('#termsaccepted').is(":checked")) { $('.error').text('please agree terms').show(); validity = false; } if($('#otherpaymentid').val() == "" && $('input[type=radio][name=paymentid]:checked').val() == 1) { $('.error').text('please enter valid payment id field').show(); validity = false; } if(!checkemail($('#otherpaymentid').val()) && $('input[type=radio][name=paymentid]:checked').val() != 0 ) { $('.error').text('please enter valid payment id field').show() validity = false; } return validity; } var checkemail = function(email) { if(email != '') { var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; return regex.test(email); } else { return false; } }
is using anonymous function wrapper 1 way approach it, tips? how 1 improve on this?
you can organize code in many ways.
1 namespace.
var myapp = myapp || {}; myapp = { init: function(){ //initialization , events $('#registrationform').on('click', ...) ... }, showpaymentidbox: function(){}, checkvalidate: function(){}, checkemail: function(){} }
2 amd/ commonjs modules
requirejs / browserify etc..
eg:- var showpaymentidbox = require('showpaymentidbox');
3 es6
eg: import "showpaymentidbox";
Comments
Post a Comment