Skip to content

Instantly share code, notes, and snippets.

@potch
Created October 23, 2023 06:05
Show Gist options
  • Save potch/f1d2fe1d1d4f72ed9d347f6b4d97cf95 to your computer and use it in GitHub Desktop.
Save potch/f1d2fe1d1d4f72ed9d347f6b4d97cf95 to your computer and use it in GitHub Desktop.
Potch's Cool Framework
// potch's cool framework!
export const signal = value => {
const subs = new Set();
const set = v => {
value = v;
subs.forEach(s => s(value));
};
return {
set value(v) { set(v) },
get value() { return value },
watch: fn => {
subs.add(fn);
return () => subs.delete(fn);
}
}
};
export const computed = (fn, ...deps) => {
const s = signal(fn(...deps));
deps.forEach(d => d.watch(v => s.value = fn(...deps)));
return s;
}
export const text = signal => el => {
const node = document.createTextNode(signal.value);
signal.watch(v => node.textContent = v);
el.append(node);
};
export const prop = (prop, signal) => el => {
el[prop] = signal.value;
signal.watch(v => el[prop] = v);
}
export const $ = (selector, scope = document) => scope.querySelector(selector);
export const $$ = (selector, scope = document) => [...scope.querySelectorAll(selector)];
export const _ = (tag, props, ...children) => {
const el = Object.assign(document.createElement(tag), props);
children.forEach(c => typeof c === 'function' ? c(el) : el.append(c));
return el;
}
import { _, text, prop, signal, computed } from './potchs-cool-framework.js'
const score = signal(0);
const name = signal("potch");
const color = computed(score => {
return score.value >= 5 ? 'color: green' : 'color: red'
}, score);
document.body.append(
_('div', { href: '#' },
_('input', {
value: name.value,
type: 'text',
oninput: e => name.value = e.target.value
}),
_('p', {},
prop('style', color),
'hi ',
text(name),
', your score is ',
text(score)
),
_('button', {
onclick: e => score.value = score.value + 1
}, 'click me')
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment