eric
eric

Reputation: 321

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

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?

Upvotes: 0

Views: 190

Answers (1)

Toby L Welch-Richards
Toby L Welch-Richards

Reputation: 817

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

Upvotes: 1

Related Questions