[英]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) 和视图(使用controllerAs语法)
<div>
{{ctrl.movies}}
</div>
When I open the page, it shows {}, then data from websocket incomes (correctly), biding to this.movies, and nothing changes. 当我打开页面时,它显示{},然后显示来自websocket收入的数据(正确),并出价到this.movies,但没有任何变化。 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. 问题不是使用ES6,而是由于角度变化检测机制不了解您的套接字以及它必须运行摘要循环这一事实。
Take a look at this tutorial . 看一下本教程 。 Socket io here was wrapped with a service that manually calls $apply on every socket event.
此处的套接字io封装了一个服务,该服务在每个套接字事件上手动调用$ apply。
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);
});
});
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.