2

I'm going through a Firebase tutorial using angular and it started by making child_added requests in a controller, but now we're refactoring and moving those requests to a service -- as we should.

However, there's some syntax being used in the service that I'm not familiar with. Here's my service that's making a child_added request to the firebase db:

app.service(‘messageService’, function() {
    var messagesRef = new Firebase(FBURL);
    return {
        childAdded: function childAdded(callback) {
            messagesRef.on(‘child_added’, function(data) {
                callback.call(this, {
                    user: data.val().user,
                    text: data.val().text,
                    name: data.name()
                });
            });
        }   
    }
}

Then in the controller we're using the service like so:

messageService.childAdded(function(addedChild) {
    $timeout(function() {
        $scope.messages.push(addedChild);
    });
});

Firstly, I'm confused as to what callback.call(this, ... is doing? Secondly, how does that line tie in with push() method in the controller?

I would greatly appreciate any explanations. Thanks!

1 Answer 1

3

call() is just a function in the JavaScript standard library (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call).

Your code:

callback.call(this, {
  user: data.val().user,
  text: data.val().text,
  name: data.name()
});

Is practically the same thing as saying:

callback({
  user: data.val().user,
  text: data.val().text,
  name: data.name()
});

function (addedChild) {...} is your callback.

Therefore, addedChild, in your code ends up just being:

{
  user: data.val().user,
  text: data.val().text,
  name: data.name()
}

Where data is the DataSnapshot of the added child, data.val() being its value and data.name() being its key.

The only thing different about using call() vs. calling the callback directly is that call allows you to specify the caller, which becomes the this object of the callback. (A lot of call* going on in that last sentence).

Sign up to request clarification or add additional context in comments.

3 Comments

Is the this keyword referring to the data snapshot?
No, this is referring to the caller of its surrounding function, which is your firebase event callback. I'm not sure what firebase calls its event callbacks with, but after a quick debugging it looks to just be undefined. Edit: undefined, not window object.
One can pass a context into the Firebase on() method, but since nothing is getting passed in, this is indeed undefined here.

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.