如何将变量传递给函数?

时间:2017-07-28 23:36:26

标签: javascript

我试图没有任何全局变量,而且我无法弄清楚如何将数据库var传递给addTrain函数。我是否需要为数据库设置全局变量?

$(document).ready(function(){

function mainProgram(){
    var config = {};        // Initialize Firebase
    var database;           // Variable to reference the database

    config = {
    apiKey: "#",
    authDomain: "#",
    databaseURL: "#",
    projectId: "#",
    storageBucket: "",
    messagingSenderId: "#"
  };
    firebase.initializeApp(config);

    database = 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();


    database.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);

 }  
});

我是否在mainProgram()调用中传入数据库?像mainProgram(数据库)?那样的东西?我想我已经把这一切都弄错了。我正处于一个编码训练营中,而且我正在努力绕过变异和范围。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用

$("#train-submit").click({arg1: "something", arg2: "something else"}, addTrain);

然后在函数定义中,您可以像

一样访问
function addTrain(event){
    event.data.arg1;
    event.data.arg2;