Setup update listeners to rerender react components (#848)

* Setup update listeners to rerender react components

* setupUpdates -> useJsUpdates
This commit is contained in:
jberg 2019-08-12 15:05:46 -07:00 committed by Jordan Eldredge
parent 8b91e6db79
commit 8628bc70f5
3 changed files with 18 additions and 7 deletions

View file

@ -1,4 +1,4 @@
import React from "react";
import React, { useEffect, useReducer } from "react";
import JSZip from "jszip";
import "./App.css";
import * as Utils from "./utils";
@ -22,6 +22,11 @@ async function getSkin() {
return await initialize(zip, skinXml);
}
function useJsUpdates(node) {
const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
useEffect(() => node.js_listen("js_update", forceUpdate));
}
function handleMouseEventDispatch(node, event, eventName) {
const rect = event.target.getBoundingClientRect();
const x = event.clientX - rect.left;
@ -66,7 +71,8 @@ function handleMouseButtonEventDispatch(
);
}
function GuiObjectEvents({ node, children }) {
function GuiObjectEvents({ Component, node, children }) {
useJsUpdates(node);
return (
<div
onMouseDown={e =>
@ -94,7 +100,9 @@ function GuiObjectEvents({ node, children }) {
onKeyUp={e => node.js_trigger("onKeyUp", e.keyCode)}
onKeyDown={e => node.js_trigger("onKeyDown", e.keyCode)}
>
{children}
<Component node={node} {...node.attributes}>
{children}
</Component>
</div>
);
}
@ -318,10 +326,8 @@ function XmlNode({ node }) {
return null;
}
return (
<GuiObjectEvents node={node}>
<Component node={node} {...attributes}>
{children}
</Component>
<GuiObjectEvents Component={Component} node={node}>
{children}
</GuiObjectEvents>
);
}

View file

@ -35,6 +35,7 @@ class GuiObject extends MakiObject {
setxmlparam(param, value) {
this.attributes[param] = value;
this.js_trigger("js_update");
return value;
}

View file

@ -29,6 +29,10 @@ class MakiObject {
this._emitter.trigger(eventName, ...args);
}
js_listen(eventName, cb) {
return this._emitter.listen(eventName, cb);
}
js_listenToAll(cb) {
return this._emitter.listenToAll(cb);
}