Angularjs socket.io service

Hi, I am creating an angularjs service that will use websockets via socket.io to communicate with the backend (node.js). I found a piece of code online, but I don’t quite understand how it works. In particular, in 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);
          }
        });
      })
    }
  };
});
+4
source share
1 answer

Here, javascript betrays its aversion to unnamed variables. The variable argumentsrefers to an array of arguments that are passed to the function. What you see is angular code, capturing an array of function arguments and passing them for use.

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

2.

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

+3

Source: https://habr.com/ru/post/1523834/


All Articles