0

I need some help understanding the code below. It is taken from: http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets

app.factory('socket', function ($rootScope) {
var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
  };

I am having problem understanding:

  1. From where did arguments come
  2. what is callback.apply and what is it doing?

1 Answer 1

1

It's basic JavaScript, nothing to do with AngularJS or Socket.io.

arguments is a "magic" variable available inside every function to access it's arguments in array-like manner.

Function#apply is a way to call a function with a different this context providing arguments as the second argument.

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

2 Comments

Controller is this: function AppCtrl($scope, socket) { socket.on('init', function (data) { $scope.name = data.name; $scope.users = data.users; }); Can you explain me the flow? I am not sure what callback.apply is invoking.
I believe the post answers your initial questions (if you agree, you can accept it). If you have more questions, feel free to create more posts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.