GitHub | Documentation | Become a Patron

Listeners triggered even though listening to different state properties



  • I have the following logic client side

    room.listen('pullPosition/:position', (change) => {
        console.log('position', change);
        if(ready && !state.isHoldEnabled) state.setPosition(change.value)
      })
    
      room.listen('pullPosition/:hold', (change) => {
        console.log('hold', change);
      })
    

    I'm experiencing and issue where if pullPosition/:position changes BOTH listeners are triggered despite not listening to the same property.... Is this how its suppose to happen by design?


  • administrators

    (Replied on GitHub: https://github.com/gamestdio/colyseus.js/issues/42)

    Hey @karneaud, when using :anything, starting with :, it will generate a wildcard regular expression, that's why both listeners are being triggered.

    You have two alternatives on this situation, which are:

    Listening to direct properties

    room.listen('pullPosition/position', (change) => {
        console.log('position attribute has changed', change.value);
    });
    room.listen('pullPosition/hold', (change) => {
        console.log('hold attribute has changed', change.value);
    });
    

    Remember that if position is a vector, you'd need to listen to its deep variables such as x and y, by using listen('pullPosition/position/x') and listen('pullPosition/position/y'). You can also use the wildcard method for this, using the same example below.

    Listening to every attribute, and check which one has changed in the change.path

    room.listen('pullPosition/:attribute', (change) => {
        console.log(change.path.attribute, 'has changed to', change.value);
    });