Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Usually the socket.io's on method is like this:

socket.on('/msg', function(data){});

But in Angular that callback has to be wrapped inside its $rootScope.$apply() method otherwise anything that happens in the callback (like changing $scope properties) doesn't update in Angular.

Here's a simple way to do that:

function socketFactory($rootScope) {
    return {
        emit: socket.emit.bind(socket),
        on: function(msg, callback) {
            socket.on(msg, function() {
                var args = arguments;
                $rootScope.$apply(function(){
                    callback.apply(socket, arguments)
                });
            });
        },
    };
};

I was able to shorten this a little bit:

on: function(msg, callback) {
    socket.on(msg, function() {
        $rootScope.$apply(callback.apply(socket, arguments));
    });
},

I'm not sure if it'll go any further but I tried:

on: function(msg, callback) {
    socket.on(msg, $rootScope.$apply.apply(null, callback));
},

which threw an error:

Uncaught TypeError: Cannot read property 'apply' of undefined socket.io.js:1194

I'm guessing $apply.apply doesn't work.

share|improve this question
    
Rather than giving a callback, why not broadcast to the rootScope and listen for that event? – Preston Van Loon Jul 13 '15 at 1:47
up vote 1 down vote accepted

.bind should've been used here instead of .apply

on: function(msg, callback) {
    socket.on(msg, $rootScope.$apply.bind($rootScope, callback.bind.apply(socket, arguments)));
},

But seeing how complicated the shortened "one-liner" becomes, expanded form was probably better:

on: function(msg, callback) {
    socket.on(msg, function(data){
        $rootScope.$apply(function(){
            callback(data);
        });
    });
},
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.