We already have a global variable available to us. How about we simply create variables right on the jQuery object. Then, in our various functions, we can simply check if they exist, implement them if they don't, or reference them if they do?
Looking at your fiddle, this can also be done pretty painlessly -- simply have each function that needs access to a global namespace either create or reference it.
$(function() {
$.bob_jsNS = $.bob_jsNS || {};
var mainurl = 'http://localhost:9000';
/* Login User */
$("#submit-login").click(function() {
userLogin();
});
function userLogin() {
$.bob_jsNS.user = $.bob_jsNS.user || {};
var myUser = $.bob_jsNS.user;
myUser.userName = $('#user').val();
var password = $('#pass').val();
// var data = $("#login-user").serialize();
var data = {
"userName": myUser.userName
}
$('#sdlc-gif').show();
// I simply reference the global namespace to get the userName.
if (myUser.userName != '' && password != '') {
// Removed for clarity. There was code here.
}
}
function requestDemo() {
/*****
* Any time I need access to any part of the global namespace,
* I should first check that it's there -- and if not, create it.
* These first few lines happen on any function that will need to get
* or set global values or functions.
***/
$.bob_jsNS = $.bob_jsNS || {};
$.bob_jsNS.user = $.bob_jsNS.user || {};
var myUser = $.bob_jsNS.user;
// If we don't have a username, set it blank.
// May not be an issue, but it may break otherwise.
var myUser.userName = myUser.userName || "";
var myUser.first = ('#firstName').val();
var myUser.last = ('#lastName').val();
var myUser.title = ('#jobTitle').val();
var myUser.email = ('#email').val();
var myUser.comments = ('#comments').val();
var myUser.app1 = ('#app1').val();
var myUser.app2 = ('#app2').val();
var myUser.app3 = ('#app3').val();
var data = {
"userName": myUser.userName,
"firstName": myUser.first,
"lastName": myUser.last,
"jobTitle": myUser.title,
"email": myUser.email,
"comments": myUser.comments,
"app1": myUser.app1,
"app2": myUser.app2,
"app3": myUser.app3
}
/***
* More code was here, abbreviated for clarity.
***/
}
/* Provide feedback form */
$("#submit-feed").click(function() {
provideFeedback();
});
/* Provide Feedback */
function provideFeedback() {
// var data = $("#provide-feed").serialize();
$.bob_jsNS = $.bob_jsNS || {}
$.bob_jsNS.user = $.bob_jsNS.user || {};
var userName = $.bob_jsNS.user.userName || "";
var q1 = $("input[name='group1']:checked").val();
var q2 = $("input[name='group2']:checked").val();
var q3 = $("input[name='group3']:checked").val();
var q4 = $("#ans4").val();
var q5 = $("#ans5").val();
var data = {
"userName": userName,
"q1": q1,
"q2": q2,
"q3": q3,
"q4": q4,
"q5": q5
}
}
});