Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 1961

Firebase listen for changes in particular field

I'm working on real time virtual room with chat using firebase. I was wondering if it's possible to listen for updates on particular field in firebase db. for example if the data is structured in a following way:

{channel_name: test-app,
  {id: unique_id_generated_automatically_by_firebase,
    {user_id: some_id,
     position: {
       current: {x:x,y:y},
       start: {x:x,y:y},
       end: {x:x,y:y}
    }
  }
  {id: unique_id_generated_automatically_by_firebase,
    {user_id: some_id,
     position: {
       current: {x:x,y:y},
       start: {x:x,y:y},
       end: {x:x,y:y}
    }
  }
} 

At the moment i'm able to listen for any changes in db like that

//reference to firebase db
var room = new Firebase("https://test-app.firebaseio.com/");
room.on("child_changed", function(snapshot) {
   //do something here; 
});

What i'm looking for is a way to listen for changes on fields position.start and position.end, but ignore position.current (those are the only fields that will get updated). The current position will be needed only when user log in to get the current positions of all users currently in the room. After that the positions will be animated on the client machine based on start and end values. I would also like to save on data transfer by not emitting changes on current position to all connected clients, but have current state when requested. Any help and suggestions much appreciated.

Upvotes: 3

Views: 5306

Answers (1)

Anant
Anant

Reputation: 7428

You can bind a .on("value") event for each field you're interested in.

var room = new Firebase("https://test-app.firebaseio.com/" + roomID);
room.child("position/start").on("value", onChange);
room.child("position/end").on("value", onChange);
function onChange(snapshot) {
  if (snapshot.name() == "start") {
    // position.start changed to snapshot.val()
  } else if (snapshot.name() == "end") {
    // position.end changed to snapshot.val()
  }
}

Upvotes: 2

Related Questions