Lukas Ruebbelke: 00:00 Hello. This is Lukas Ruebbelke. I'm going to show you how to use Firebase event handlers in AngularJS. Firebase event handlers are useful when you want to be notified of a remote event so that you can respond to it in your local client.
00:21 For instance, let's say the remote collection is updated and you want to listen for that change event so that you can put up an alert or a dialog to the user indicating that "Something has happened, and we are updating this."
00:41 How we do this is using the on method that we attach to Firebase collection. In this case, it's scope.items. This method takes two parameters, an event handler for the specified event and the event handler.
01:01 Let's get started with the loaded event. We are going to listen for the loaded event. In our event handler, we are going to simply log to the console that items have loaded.
01:26 Let's refresh the page here. You can see that items loaded was logged to the console. The other event that we can listen for is when the collection has changed.
01:44 We will listen for the change event. In our event handler, we are going to just log to the console items changed. Let's refresh the page. The interesting thing here is that you'll notice that we've logged items changed to the console 20 times before the loaded event handler was fired.
02:14 The reason being is that the change event is fired every time that your local collection is modified. The way that Firebase actually loads your data is in incremental pieces. Because we have 20 items, as each one of those is being added to the collection, it's firing a change event.
02:40 We need to take that into account. The way that we do that is using a technique that was recommended to me by the Firebase guys. That is to set a flag and once the collection is loaded, set that flag to "true."
03:01 From here, we are simply going to say, "The scope is not loaded. We are going to return and not proceed with the remainder of this method."
03:15 Let's hop into the browser, refresh it. You will see that we did not fire any change events. If I set this to 2,000 and I update it, you will see that it has changed or the change event was fired. That is how to use Firebase events.
03:38 You have two events that you can listen to, loaded and change. One other thing worth mentioning is that if you want to detach from a particular event, you can use the opposite of the on method, which is off. You just pass in the event that you no longer want to listen for.
03:58 As well as if you want to break the connection to the Firebase collection entirely, you can call off and not pass any event parameters. It would just detach from the collection entirely, and you will no longer receive real-time updates as that collection changes.
04:18 This concludes this lesson. Stay tuned for more videos on this topic, and I will catch you next time.