Skip to content

Instantly share code, notes, and snippets.

@rgchris
Last active Feb 22, 2021
Embed
What would you like to do?
Await Pattern
Rebol [
Title: "Await Pattern"
Date: 22-Feb-2021
Author: "Christopher Ross-Gill"
]
; Establish a global namespace that we can use
;
js-do {
window.ReplPad = window.ReplPad || {}
// Used to stringify an EVENT - https://stackoverflow.com/a/34519193
// Not used in current iteration
//
ReplPad.stringify = function (e) {
let k
const obj = {
'content': e.target.innerText
}
for (k in e) {
obj[k] = e[k];
}
return JSON.stringify(
obj, (k, v) => {
if (v instanceof Node) return 'Node'
if (v instanceof Window) return 'Window'
return v
}, ' '
)
}
// Used to add given DIVs to BODY
//
ReplPad.show = function(...divs) {
for (var i = 0; i < divs.length; i++) {
document.body.appendChild(divs[i])
}
}
// Used to remove given DIVs from BODY
//
ReplPad.hide = function(...divs) {
for (var i = 0; i < divs.length; i++) {
document.body.removeChild(divs[i])
}
}
// Used to attach an actor as a 'click' listener for given DIVs
//
ReplPad.attach = function (actor, ...divs) {
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener(
'click', actor
)
}
}
// Common styles for our DIVs
//
ReplPad.common = 'position:absolute;width:100px;height:100px;top:0;color:white;'
// Red DIV
//
ReplPad.red = load(
'<div style="' + ReplPad.common + 'background:red;right:100px;">I am RED box</div>'
)
// Green DIV
//
ReplPad.green = load(
'<div style="' + ReplPad.common + 'background:green;right:0;">I am GREEN box</div>'
)
}
; Here we'll place a red div and a green div (defined above)
; and add our handler to their 'click' listener. When clicked,
; it will ding the awaiter with either 'red' or 'green'.
;
; All of the DOM stuff here--creation, listener assignment,
; appendage and removal--would presumably eventually be
; handled on the Ren-C side.
;
js-do {
ReplPad.show(
ReplPad.red, ReplPad.green
)
ReplPad.actor = function(event) {
let clicker = (event.target == ReplPad.red)
? 'red'
: 'green'
if (clicker == 'red') {
ReplPad.hide(
ReplPad.red, ReplPad.green
)
}
// Return to Ren-C!
ReplPad.wake(
reb.Text(clicker)
)
}
ReplPad.attach(
ReplPad.actor,
ReplPad.red, ReplPad.green
)
}
; We establish an awaiter that, when called will wait for ReplPad.wake to be called
;
await: js-awaiter [] {
return new Promise(
function(resolve, reject) {
ReplPad.wake = resolve
}
)
}
; The goal is to place this in a loop that will take the event and respond
; until 'done' condition is met
;
until [
(probe await) = "red"
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment