GitHub Documentation

How to reset callbacks for state changes?



  • Hello everybody. I have two questions about resetting callbacks for state changes for data based on schema:

    #1

    Set onChange callback for collection of primitive types based on schema:
    https://docs.colyseus.io/state/schema/#onchange-instance-key

    room.state.players.onChange = (player, key) => {
        console.log(player, "have changes at", key);
    };
    

    Question: How to reset that callback? Is the following correct?

    room.state.players.onChange = undefined;
    

    #2

    Set listen callback on single property based on schema:
    https://docs.colyseus.io/state/schema/#listenprop-callback

    state.listen("currentTurn", (currentValue, previousValue) => {
        console.log(`currentTurn is now ${currentValue}`);
        console.log(`previous value was: ${previousValue}`);
    });
    

    Question: How to reset that callback? The following does not work (at least not in TypeScript)!

    state.listen("currentTurn", undefined); // compiler error, at least in TypeScript
    

    P.S.:
    Plenty other features of Colyseus work really fine for me. 👍


  • administrator

    Hi @TeeTeeHaa!

    The .listen() method returns a callback that is going to unregister itself.

    Example:

    const removeListener = state.listen("currentTurn", () => {
      /* do stuff */
    });
    
    // call `removeListener()` to remove it!
    removeListener();
    

    Thanks for the heads-up, this has been included in the docs now: https://github.com/colyseus/docs/commit/945a4043ce8655756d9912a12be0bc4ae9c0eea5

    Hope this helps! Cheers!


 

© 2021 Lucid Sight, Inc