I'm trying to avoid using global variables and I'm facing some difficulties in figuring out how to pass the database variable into the addTrain function. Do I necessarily need to use global variables for the database?
$(document).ready(function(){
function mainProgram(){
var config = {}; // Initialize Firebase
var db; // Variable to reference the database
config = {
apiKey: "#",
authDomain: "#",
databaseURL: "#",
projectId: "#",
storageBucket: "",
messagingSenderId: "#"
};
firebase.initializeApp(config);
db = firebase.database();
$("#train-submit").click(addTrain);
}
//calls the main function
mainProgram()
// add train function
function addTrain(event){
event.preventDefault();
console.log("clicked");
var name; // Train name
var destination; // Train destination
var arrivalTime; // inputted arrival time
var frequency; // How often train arrives
var timeStamp; // FB timestamp
var formatTime; // Format for moment.js
var convertedTime; // converted time
var displayTime; // converted time for displaying in DOM
var timeLeft; // time left until next train
name = $("#train-name").val().trim();
destination = $("#train-destination").val().trim();
arrivalTime = $("#train-time").val().trim();
frequency = $("#train-frequency").val().trim();
formatTime = "HH mm";
convertedTime = moment(arrivalTime, formatTime);
displayTime = moment(convertedTime).format("HH:mm")
timeLeft = moment(convertedTime).fromNow();
db.ref("/train-data").set({
name: name,
destination: destination,
frequency: frequency,
arrivalTime: arrivalTime,
timeStamp: firebase.database.ServerValue.TIMESTAMP
})
console.log("input captured: " + name);
console.log("input captured: " + destination);
console.log("input captured: " + frequency);
console.log("input captured: " + arrivalTime);
console.log("converted convertedTime: " + convertedTime);
console.log("converted displayTime: " + displayTime);
console.log("converted timeLeft: " + timeLeft);
}
});
Should I include the database parameter in the mainProgram() call? Like mainProgram(database)? Or something similar? I feel like I've structured this incorrectly. I'm currently enrolled in a coding bootcamp and I'm really struggling with grasping the concept of passing in variables and scope. Any assistance would be greatly appreciated.