Sonali Gupta
Sonali Gupta

Reputation: 308

AngularJs and SocketIo

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?

Upvotes: 0

Views: 72

Answers (1)

Pavlo
Pavlo

Reputation: 44889

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.

Upvotes: 1

Related Questions