如何在Aurelia中使用socket.io

How to use socket.io in Aurelia

本文关键字:socket io Aurelia      更新时间:2023-09-26

我正在尝试将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 = '';
    }
}