簡體   English   中英

如何使用Firebase在javascript中使局部變量成為全局變量?

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

我想通過firebase api提取一個值並將其設為全局變量,以便可以在代碼中的其他位置引用它

我希望下面的代碼在從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());

使用異步編程,您只能在回調內部或從那里調用的函數中使用響應,並將數據傳遞給該響應。 您不能將其填充到全局變量中,以嘗試解決響應是異步的這一事實。 您也不能從異步回調中返回值,並且不能期望從主機函數返回該值。 主機函數已經完成執行,回調在一段時間后被調用。

這是一種可行的方法:

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

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

要閱讀更多有關處理異步響應的選項的信息,您可以閱讀以下有關ajax調用的答案,但是概念是相同的: 如何從異步調用返回響應?

您應該在$( 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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM