Skip to content

Instantly share code, notes, and snippets.

@OperationDarkside
Created December 7, 2019 00:32
Show Gist options
  • Save OperationDarkside/031bf87c57e6690aca01aca5a39cb8b4 to your computer and use it in GitHub Desktop.
Save OperationDarkside/031bf87c57e6690aca01aca5a39cb8b4 to your computer and use it in GitHub Desktop.
First successfull attempt at creating a component aware DOM with Message sending and receiving
#include <vector>
#include <map>
#include <memory>
#include <functional>
#include <iostream>
struct comp;
struct relay {
int nextId = 0;
std::function<void(int, comp*)> addFunc;
void registerComp(comp* c){
addFunc(nextId++, c);
}
void receivedClick() {
std::cout << "ReceivedClick" << std::endl;
}
};
struct comp {
int id = -1;
relay* r;
comp* parent;
comp(){
}
virtual ~comp() = default;
virtual void recieveCmd() = 0;
};
struct root_comp : public comp {
std::unique_ptr<comp> child;
root_comp() {
comp::parent = nullptr;
}
virtual void recieveCmd() override {
};
void setChild(std::unique_ptr<comp>&& c){
child = std::move(c);
child->parent = this;
r->registerComp(child.get());
}
};
struct complist : public comp {
std::vector<std::unique_ptr<comp>> children;
complist(){
}
};
struct clickable : public comp {
virtual void recieveCmd() override {
if(!r) return;
r->receivedClick();
};
};
struct DOM {
relay r;
root_comp root;
std::map<int, comp*> index;
DOM() {
r.addFunc = [&](int id, comp* c) {
c->id = id;
c->r = &r;
index.emplace(id, c);
};
root.r = &r;
root.id = r.nextId++;
index.emplace(root.id, &root);
}
void sendMessage(int id){
index.at(id)->recieveCmd();
}
};
int main () {
DOM dom;
dom.root.setChild(std::make_unique<clickable>());
dom.sendMessage(1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment