I’m exploring a theoretical concept rather than seeking a practical solution, aiming to create a lightweight framework for binding scalar data to HTML element properties, enabling them to update automatically when the source value changes. The focus is on achieving a syntactically elegant approach that facilitates IDE code completion and enhances developer convenience. I understand that JavaScript Proxies could be involved, but my main challenge lies in crafting the syntax I envision.
For example, I’m imagining a simple data-binding method like the following:
let exampleVariable = "hello";
let element = MyFramework.getElementById("example-div"); // returns a proxied HTMLElement with extra methods
element.bind("textContent", exampleVariable);
// later...
exampleVariable = "world"; // element.textContent updates automatically
I realize this won’t directly work with primitive values, so I’m fine with implementing a state object that can be proxied:
let appState = MyFramework.createState(); // returns a proxy for the state object
appState.exampleVariable = "hello";
let element = MyFramework.getElementById("example-div");
element.bind("textContent", appState.exampleVariable);
The tricky part arises in accessing the key “exampleVariable” within the bind() method, instead of merely retrieving its value. I considered using a proxy in createState()
to modify the getter, but I need it to conditionally return the property name only within the context of the bind() function. I’m hoping to avoid requiring something like element.bind("textContent", appState, "exampleVariable");
or redundant calls like element.bind("textContent", appState.exampleVariable);
, which could lead to errors.
Alternatively, I’m open to something like appState.exampleVariable.bind(element, "textContent");
, but that won’t function as expected since exampleVariable
is still a primitive and lacks custom properties. I wonder if intercepting the first access of appState.exampleVariable
, that would allow the bind functionality, might be a solution. However, this would still limit how appState.exampleVariable
can be used in simpler contexts, potentially leading to cumbersome alternatives like appState.exampleVariable.set("new value");
or appState.exampleVariable.get();
.
I’m reaching the limits of my JavaScript internals knowledge and am curious if I’ve overlooked any simple solutions. If you feel there’s a better way to tackle this elegantly, I’m open to suggestions, but I prefer to explore my current path unless there truly are insurmountable obstacles.