Raston Raston - 1 year ago 56
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));

this.movies = JSON.parse(data);

and view (using controllerAs syntax)


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 Source

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;
        $rootScope.$apply(function () {
          callback.apply(socket, args);