Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use socket.io in Aurelia

I am trying to use socket.io with the aurelia framework. When loading the page, the data is pulled from the socket server, but afterwards, it doesn't listen.

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 = '';
    }
}

I love aurelia, but I keep failing with integrating socket.io.

like image 385
Matthias Feldmann Avatar asked Dec 29 '25 20:12

Matthias Feldmann


1 Answers

Try binding your listener in activate() instead of 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 = '';
    }
}
like image 98
Todd Price Avatar answered Dec 31 '25 10:12

Todd Price