Simple todo
Note
cstojs-cli 0.1.3 is used.
cstojs_options.xml:
<ProjectOptions>
<Output Folder="Output" />
<Option KeepBraceOnTheSameLine="true" />
<File Source="./Program.cs" />
</ProjectOptions>
Program.cs:
using CSharpToJavaScript.APIs.JS;
using static CSharpToJavaScript.APIs.JS.Ecma.GlobalObject;
GlobalThis.Window.Document.AddEventListener("DOMContentLoaded", (Event e) =>
{
HTMLElement body = GlobalThis.Window.Document.Body;
HTMLFormElement todoForm = (body as ParentNode).QuerySelector<HTMLFormElement>("#TodoForm");
HTMLUListElement ulList = (body as ParentNode).QuerySelector<HTMLUListElement>("#List");
todoForm.AddEventListener("submit", (Event e) =>
{
e.PreventDefault();
FormData data = new FormData(todoForm);
AddEntry(data, ulList);
Console.WriteLine(data);
}, true);
}, true);
void AddEntry(FormData data, HTMLUListElement ulList)
{
HTMLDivElement divElement = (HTMLDivElement)GlobalThis.Window.Document.CreateElement("div");
string todo_str = data.Get("todo") + " ";
Text todoText = GlobalThis.Window.Document.CreateTextNode(todo_str);
HTMLButtonElement buttonElement = (HTMLButtonElement)GlobalThis.Window.Document.CreateElement("button");
buttonElement.TextContent = "Done";
HTMLLIElement liElement = (HTMLLIElement)GlobalThis.Window.Document.CreateElement("li");
divElement.AppendChild(todoText);
divElement.AppendChild(buttonElement);
liElement.AppendChild(divElement);
ulList.AppendChild(liElement);
buttonElement.AddEventListener("click", ()=> { DeleteEntry(liElement); }, true);
}
void DeleteEntry(HTMLLIElement li)
{
(li as ChildNode).Remove();
}
Translated js:
globalThis.window.document.addEventListener("DOMContentLoaded", (e) => {
let body = globalThis.window.document.body;
let todoForm = body.querySelector("#TodoForm");
let ulList = body.querySelector("#List");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
let data = new FormData(todoForm);
AddEntry(data, ulList);
console.log(data);
}, true);
}, true);
function AddEntry(data, ulList) {
let divElement = globalThis.window.document.createElement("div");
let todo_str = data.get("todo") + " ";
let todoText = globalThis.window.document.createTextNode(todo_str);
let buttonElement = globalThis.window.document.createElement("button");
buttonElement.textContent = "Done";
let liElement = globalThis.window.document.createElement("li");
divElement.appendChild(todoText);
divElement.appendChild(buttonElement);
liElement.appendChild(divElement);
ulList.appendChild(liElement);
buttonElement.addEventListener("click", ()=> { DeleteEntry(liElement); }, true);
}
function DeleteEntry(li) {
li.remove();
}
See the full source code: https://github.com/TiLied/CSTOJS_Pages/tree/main/tutorials/SimpleTodo_Example
Live example: