简体   繁体   中英

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?

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);
        });
      });
    }
  };
});

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