简体   繁体   中英

Angular binding not updating with socket.io broadcast

I have a server variable named currentPlayer that binds properly in the emit 'init' call, but won't bind in my broadcast.emit. The variable turnNumber which is passed through from the client first updates properly. When the pass event is fired I can see currentPlayer switching values in the terminal, but I'm stumped as to why it doesn't update in the view.

I had some trouble binding to primitive types before, so I tried going an extra step and assigning currentPlayer to an object array: $scope.globalVars = [{ currentPlayer: data.currentPlayer }], but that didn't help.

//server
var currentPlayer = 1;
socket.emit('init', {
    currentPlayer: currentPlayer
});
socket.on('pass', function (data) {
    currentPlayer = currentPlayer == 1 ? 2 : 1;
    console.log(currentPlayer);
    socket.broadcast.emit('pass', {
        number: data.turnNumber,
        currentPlayer: currentPlayer
    });
});

//client
socket.on('init', function (data) {
    $scope.globalVar.currentPlayer = data.currentPlayer;
});
socket.on('pass', function (data) {
    $scope.globalVar.turnNumber = data.number;
    $scope.globalVar.currentPlayer = data.currentPlayer;
});
//click event
$scope.globalVar.turnNumber++;
socket.emit('pass', {
    turnNumber: $scope.globalVar.turnNumber
});

<!-- html -->
{{globalVar.currentPlayer}} {{globalVar.turnNumber}}

UPDATE:

I realized I could handle the current turn logic in my angular controller. I'm no longer changing the variable on the server and trying to pass it back to the client. Maybe as Chandermani says it's simply out of angular's context.

//server
socket.on('pass', function (data) {
    socket.broadcast.emit('pass', {
        number: data.turnNumber,
        currentPlayer: data.currentPlayer
    });
});
//client
socket.on('pass', function (data) {
    $scope.globalVar.turnNumber = data.number;
    $scope.globalVar.currentPlayer = data.currentPlayer;
});
//click event
$scope.globalVar.currentPlayer = $scope.globalVar.currentPlayer == 1 ? 2 : 1;
$scope.globalVar.turnNumber++;
socket.emit('pass', {
    turnNumber: $scope.globalVar.turnNumber,
    currentPlayer: $scope.globalVar.currentPlayer
});

These calls seem to be execution outside the anuglar context. Try to use $scope.$apply in the socket.on handlers, like

socket.on('pass', function (data) {
   $scope.$apply(function() {
    $scope.globalVar.turnNumber = data.number;
    $scope.globalVar.currentPlayer = data.currentPlayer;
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM