Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Article] How to write custom event listener for C# changes in React #8

Open
Muchaszewski opened this issue Dec 6, 2022 · 0 comments

Comments

@Muchaszewski
Copy link

Example code to put in the article

C#

    public Action AddKeyPressListener(object callback)
    {
        var cb = ReactUnity.Helpers.Callback.From(callback);
        Action<string> listener = null;
        listener = (val) => {
            if (cb?.callback == null) // Check if we lost reference to cb, if so unsubscribe because we probably lost handle.
            {
               OnKeyPress  -= listener;
               return;
            }
            cb.Call(val);
        }

        OnKeyPress += listener;

        return () => OnKeyPress -= listener;
    }

TSX

  const [key, setKey] = useState("");
  useEffect(() => {    
    const unsubscribe = Global.Instance.AddKeyPressListener((input: string) => {
      setKey(input);
    });
    // Get current value before hook is called
    const input= Global.Instance.LastKeyPressed;
    setKey(input);
    return () => unsubscribe();
  }, []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant