How do I display the followers count in real time

2019-09-20 10:55发布

I have an application where users can follow other users. I want to have a real-time update system, display the total count of followers a user has.

I've just started playing around with Firebase and Pusher, but I don't understand one thing - will each user have their own 'channel'? How would I handle such thing as a follower counter update?

I followed the tutorial and saw that push method can create lists, so one solution I can see is having a list of all the users, each user being an object something like this:

{ username: 'john_doe', follower_count: 6 }

But I don't understand how would I actually track it on the front end? Should I have a filter, something like this?

var user = users.filter(function(user) { return user.username === 'john_doe'; });
// code to display user.follower_count

Or is there a different way that I'm missing?

2条回答
仙女界的扛把子
2楼-- · 2019-09-20 11:08

Most of Firebase logic is based on listeners, you can add a listener to events happening in your collections and when those events happen, you do something.

One way to go about this would be:

var myFollowerListRef = new Firebase(PATH_TO_YOUR_COLLECTION);
myFollowerListRef.on("value", function(snapshot) {
    console.log(snapshot.length);
});

This way, every time your follower collection changes, the asynchronous function fires and you can do what you want with the fresh data.

For more information:

https://www.firebase.com/docs/web/guide/retrieving-data.html

Hope this helps, I'm still a beginner in Firebase.

查看更多
The star\"
3楼-- · 2019-09-20 11:10

@Th0rndike's approach is the simplest and works fine for relatively short lists. For longer lists, consider using a transaction. From the Firebase documentation on saving transactional data:

var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

But I recommend that you read the entire Firebase guide. It contains solutions for a lot of common use-cases.

查看更多
登录 后发表回答