0

I am working on a Hybrid app written in Ionic-1 that uses Angular-1 javascript library and HTML-5 to create hybrid apps.

In my code I am connecting to Firebase to fetch some data:

MyCtrl:

angular.module('myctrl.controller', [])
  .controller('MyCtrl', function () {
    $ionicPlatform.ready(function () {
      try {
            var userRef = firebase.database().ref().child("users/" + loggedInUser.userName + "/details");             
            userRef.on('child_added', function(snapshot, prevChildKey) {
              var newUser = snapshot.val();
              console.log("New user " + JSON.stringify(newUser));
          });
        }
     });
  });

Now as I understand that controllers are re-instantiated every time views they are attached to are re-created. However, in my app even if I am outside the view which is attached to this controller, and add a user in firebase, this code gets executed. It confuses me as this code should have been garbage collected once view is replaced by another one. Does it mean that this on() method somehow getting attached to $rooScope?

1 Answer 1

1

firebase events won't got deregistered automatically, you have to unregister it manually when leaving controller.

var userRef;
$ionicPlatform.ready(function () {
  try {
    userRef = firebase.database().ref().child("users/" + loggedInUser.userName + "/details");             
    userRef.on('child_added', function(snapshot, prevChildKey) {
      var newUser = snapshot.val();
      console.log("New user " + JSON.stringify(newUser));
    });
  }
});

$scope.$on('destroy', function() {
  if (userRef) userRef.off();
})
Sign up to request clarification or add additional context in comments.

8 Comments

I see. Thanks for your ans. Do you know conceptually how does this userRef survives even when controller is destroyed? Shouldn't it be gone like any other variable that we define inside a controller?
@Richeek nope, this is not about userRef variable, when you call userRef.on, it will add a task to your browser's scheduler which won't be recycled unless you manually release it.
Thanks! That gives me some peace of mind :) I tried looking for on() method docs earlier, but all I could find is jQuery on() method [api.jquery.com/on/] . Is it the same? May I ask if there are any docs where I can learn how these event handlers work?
@Richeek see documentation here. firebase.google.com/docs/reference/js/…
@Richeek see whether these make any sense. quora.com/… blog.risingstack.com/asynchronous-javascript
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.