Raston Raston - 6 months ago 11
Javascript Question

Two-way binding doesn't work in ES6

Consider this code

export class TestController {
constructor() {
this.socket = io();
this.movies = {};
this.socket.emit('getAllMovies', '');
this.socket.on('allMovies', this.listMovies.bind(this));
}

listMovies(data){
this.movies = JSON.parse(data);
console.log(this.movies);
}
}


and view (using controllerAs syntax)

<div>
{{ctrl.movies}}
</div>


When I open the page, it shows {}, then data from websocket incomes (correctly), biding to this.movies, and nothing changes. Looks like two-way biding is broken. Anyone has idea why?

Answer

The problem is not w/ ES6 but comes from the fact that angular change detection mechanism is not aware about your socket and the fact that it has to run digest loop.

Take a look at this tutorial. Socket io here was wrapped with a service that manually calls $apply on every socket event.

app.factory('socket', function ($rootScope) {
  var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        //NB!
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    }
  };
});
Comments