2014-10-30 193 views
2

我想通过firebase API拉一个值,并使其成为一个全局变量,以便我可以参考它在代码中的其他位置如何在JavaScript中使用Firebase将本地变量设置为全局变量?

我想让下面的代码工作,从火力点,并且可以使用它以外(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); 

我试着使用var没有运气定义它下面的功能(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); 

我也试着将它定义作为一项功能没有运气: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()); 
+0

你*不*在这种情况下。请参阅http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call和http://stackoverflow.com/questions/500431/what-is-the-scope -of-variables-in-javascript – user2864740 2014-10-30 01:36:42

回答

1

声明全局变量使用异步编程,你只能使用回调内或从那里通过调用一个函数响应数据。您不能将其填充到全局变量中,以尝试解决响应异步的问题。您也无法从异步回调中返回值,并期望从主机函数返回值。主机功能已经完成执行,稍后调用回调。

这里,将工作的一种方式:

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

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

要阅读了很多关于你的选择处理异步响应,你可以看到这个答案大约是一个Ajax调用,但概念是相同的:How do I return the response from an asynchronous call?

-1

你应该之外的$(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); 
}); 
+2

'ref.on'是一个异步操作。 – user2864740 2014-10-30 01:37:27

+0

试过这里:http://jsfiddle.net/chrisguzman/jb4qLxtb/3/。有没有办法让它不同步? – Chris 2014-10-30 01:37:44

+0

@Chris号异步是异步的,必须如此使用。这实际上是一件好事(在浏览器JavaScript中),尽管要习惯它有点难。使用Promise可以极大地简化逻辑:但它们只是变相的回调。 – user2864740 2014-10-30 01:40:19