4

Hi I'm building an angularjs service that will use websockets via socket.io to communicate with backend (node.js). I found a snippet of code online but I don't quite understand how it works. Specifically on the lines under "var args = arguments". Help?

angularjs_service.js

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);
          }
        });
      })
    }
  };
});

1 Answer 1

3

This is where javascript betrays its aversion to unnamed variables. The variable arguments refers to an array of arguments that are passed in to a function. What you see there is angular code grabbing an array of the function's arguments and passing them to apply.

function(myVar1, myVar2){
    console.log(arguments.length);
}

Would output 2.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

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

3 Comments

ok thanks. How about $rootScope.$apply(function () { callback.apply(socket, args); }); What are these lines doing?
This framework is well documented on the angular website, since it is an angular specific question. docs.angularjs.org/api/ng.$rootScope.Scope
If this has answered your question, I would appreciate if you accepted it! :D

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.