简体   繁体   中英

How to make a local variable a global variable in javascript with firebase?

I'd like pull a value via firebase api and make it a global variable, so that I can refer to it else where in the code

I'd like for the below code to work where I pull a value from firebase and can use it outside of the function ( http://jsfiddle.net/chrisguzman/jb4qLxtb/ )

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});

alert(Variable);

I've tried defining it with var below with no luck ( http://jsfiddle.net/chrisguzman/jb4qLxtb/1/ )

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

var MyVariable = ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});


alert(MyVariable);

I've also tried to define it as a function with no luck: http://jsfiddle.net/chrisguzman/jb4qLxtb/2/

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

function myFunction() { ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});};


alert(myFunction());

With asynchronous programming, you can only use the response inside the callback or in a function you call from there and pass the data to. You can't stuff it into a global variable to try to work around the fact that the response is asynchronous. You also can't return a value form an asynchronous callback and expect that value to be returned from the host function. The host function has already finished executing and the callback is called some time later.

Here's one way that would work:

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    alert(Variable);
});

To read a lot more about your options for handling an async response, you can read this answer which is about an ajax call, but the concept is the same: How do I return the response from an asynchronous call? .

You should declare global vars outside of $( document ).ready(function()

var MyVariable = '';
$( document ).ready(function() {
var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

MyVariable = ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});


alert(MyVariable);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM