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?
-
(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 asx
andy
, by usinglisten('pullPosition/position/x')
andlisten('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); });
-
Sorry to reply to an old post but this was the one that finally helped me understand how to use listen so I thought it might be helpful to clarify for other users who are as dense as I am.
The documentation for listen at https://docs.colyseus.io/client-state-synchronization/ is painfully terse and confusing especially in how it uses the colon (:). From my understanding, if you have something like the following as your state:
{foo: bar: {baz: 'somevalue'} }
then you can listen for baz via
room.listen('foo/bar/baz', ...)
or via something like
room.listen('foo/:wildcard_1/:wildcard-2', ...)
That is you can either use the exact path or use wildcards but the text after the colon has no special meaning. I kept thinking that the
:id
and:attribute
wildcards in the docs had a special meaning.Hope that helps others who got confused like me.
Thanks again.