javascript – 如何在Aurelia中使用socket.io

我试图使用socket.io与aurelia框架.
加载页面时,数据从套接字服务器中提取,但之后,它不会监听.

import io from 'socket.io-client';
var socket = io.connect( 'http://localhost:3000' );

export class Settings {
    newstate = '';

    constructor() {
        socket.on( 'users',   // <- only works once (when loading the page) but doesn't listen after
            function ( userlist ) {
                this.users = userlist;
            }.bind( this ) );
    }

    addstate() {
        socket.emit( 'add state', this.newstate ); // <- works flawless
        this.newstate = '';
    }
}

我喜欢aurelia,但我一直没有集成socket.io.

最佳答案
尝试在activate()而不是constructor()中绑定您的侦听器.

import io from 'socket.io-client';
var socket = io.connect( 'http://localhost:3000' );

export class Settings {
    newstate = '';

    activate() {
        socket.on( 'users',   // <- only works once (when loading the page) but doesn't listen after
            function ( userlist ) {
                this.users = userlist;
            }.bind( this ) );
    }

    addstate() {
        socket.emit( 'add state', this.newstate ); // <- works flawless
        this.newstate = '';
    }
}

转载注明原文:javascript – 如何在Aurelia中使用socket.io - 代码日志