firebase读取.on('value')不起作用

时间:2013-07-22 13:29:34

标签: firebase

此脚本不适用于我。

我知道问题出在.on('value')函数中,但我不知道它是什么。

这是我的剧本:

$(document).ready(function(){

//dynamic content switching inside the content section
function writeContent(page){
    //setting post to default error message
    var post = "Sorry, This page is undergoing maintenance.";
    //firebase data reference for the clicked link's content
    var dataRef = new Firebase("https://cityartist.firebaseio.com/"+page);
    //inserting the available content to the 'post' variable 
    dataRef.on("value",function(snapshot){
        if(snapshot.val() != null){
            post = snapshot.val();
            alert("post="+post);
        }   
    });
    //showing content in the content section and changing the page's title
    $("#content").append("<article class='post'><p>"+post+"</p></article>");
    $("title").text("CityArtist.org - "+page);
}

//switching pages using the navigation bar
$(".menu_link").click(function(){
    writeContent($(this).attr("name"));
});
 });

2 个答案:

答案 0 :(得分:2)

Firebase中的回调通常是异步触发的,因为Firebase必须等待数据到达。因此,你的on('value')回调代码被调用/ after / the // //显示内容... ...代码。你可以试试这个:

dataRef.on("value",function(snapshot){
    if(snapshot.val() != null){
        post = snapshot.val();
        alert("post="+post);
    }
    //showing content in the content section.
    $("#content").append("<article class='post'><p>"+post+"</p></article>");
});

答案 1 :(得分:0)

您需要在回调中执行DOM更改(例如,在Firebase返回数据后)。这是在上下文中:

$(document).ready(function(){

//dynamic content switching inside the content section
function writeContent(page){
    //setting post to default error message
    var post = "Sorry, This page is undergoing maintenance.";
    //firebase data reference for the clicked link's content
    var dataRef = new Firebase("https://cityartist.firebaseio.com/"+page);
    //inserting the available content to the 'post' variable 
    dataRef.on("value",function(snapshot){
        if(snapshot.val() != null){
            post = snapshot.val();
            alert("post="+post);
            //showing content in the content section and changing the page's title
            $("#content").append("<article class='post'><p>"+post+"</p></article>");
            $("title").text("CityArtist.org - "+page);
        }   
    });
}

//switching pages using the navigation bar
$(".menu_link").click(function(){
    writeContent($(this).attr("name"));
});
 });