If I restructure data for use, how can I make Firebase automatically update it?

流过昼夜 提交于 2019-12-25 14:24:13

问题


If I use:

var ref = new Firebase("https://myURL.firebaseio.com/");                
var sync = $firebase(ref);                                
var firebaseData= sync.$asObject();

firebaseData will change as data from https://myURL.firebaseio.com/ changes. They will be in sync.

If I restructure data, and define it as some new variable var newStructure, how can I get it to sync with https://myURL.firebaseio.com/ or firebaseData?

Is there a way I can watch for changes in firebaseData and recall the restructuring method?

Is there a way to know what specifically changed in firebaseData and make only relevant changes to newStructure?

Is there a way that newStructure can sync directly with Firebase, albeit have data parsed with a different structure?


回答1:


Your variable firebaseData represents your firebase collection.

All changes you make to firebaseData will be syncronized across connections:

var ref = new Firebase("https://myURL.firebaseio.com/");                
var sync = $firebase(ref);                                
var firebaseData = sync.$asObject();

You can watch to see if any changes have been made to the object:

firebaseData.$watch(function(event){
    console.log("Change made to this firebase object");
    // Then you can call a function which could restructure your data:
    restructureData(firebaseData, event);
});

So your restructureData function could look like this:

var restructureData = function(firebaseObj, event){
    // This function updates firebase on every change to firebase
    // But we don't want to update it again after running this function
    if(event.key === "changesMadeToFirebase") return;
    firebaseObj.changesMadeToFirebase += 1;
    firebaseObj.$save().then(function(){
        console.log("data restructured");
    }, function(err){
        console.log("There was an error:", err);
    });
};

This allows you to check how many changes have been made to firebase, except for the changes to the field "changesMadeToFirebase"

Although this is a very small example, you will be able to find much more here:

https://www.firebase.com/docs/web/libraries/angular/api.html



来源:https://stackoverflow.com/questions/27179400/if-i-restructure-data-for-use-how-can-i-make-firebase-automatically-update-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!