الأمثلة
أمثلة عملية، وعروض حيّة.
اختر مثالًا لتفتحه بملء الشاشة: المعاينة الحية وكوده المصدري جنبًا إلى جنب.
اختر مثالًا لتفتحه بملء الشاشة: المعاينة الحية وكوده المصدري جنبًا إلى جنب.
الـ prop العادية تُقرأ مرة واحدة وقت بناء الـ component، أما الـ prop الدالة فتُعاد قراءتها مع كل update(). والـ component نفسه يُنفَّذ مرة واحدة فقط في الحالتين، وعدّاد الـ mount شاهد على ذلك.
The mount count never moves: update() re-runs the functions and patches text. The static card keeps the values it was built with, by design.
import 'nuclo' let cart = 2 let user = { name: 'Ada', plan: 'Pro' } let updates = 0 let mounts = 0 const price = () => cart * 9 // Every component below carries mounted(). It counts each time a node // is built, and refreshes only the "stats" scope (not the whole page). const mounted = () => on('mount', () => { mounts++ queueMicrotask(() => update('stats')) }) const commit = () => { updates++; update() } const row = { style: { display: 'flex', flexWrap: 'wrap', gap: '6px' } } // A component is a plain function. What it is passed decides what // can change later: // a value is read once, when the component is built // a function is a dynamic value, read again on every update() // Either way the component itself runs once. update() never calls // it again; it only re-runs the functions inside it. function Stat(label: string, value: () => string | number) { return span(mounted(), label, ' ', b(() => String(value()))) } // Static: built with a snapshot. Rename the user and it stays "Ada". function Profile(u: { name: string; plan: string }) { return div( mounted(), div(h3(u.name), small('static: built with its values')), span(`plan ${u.plan}`), ) } // Dynamic: reads through a function, so a new user object shows up. function LiveProfile(u: () => { name: string; plan: string }) { return div( mounted(), div(h3(() => u().name), small('dynamic: reads a function')), span(() => `plan ${u().plan}`), ) } export const App = () => div( div(scope('stats'), span('mounts ', b(() => String(mounts))), span('updates ', b(() => String(updates)))), div(row, Stat('items', () => cart), Stat('price', () => `$${price()}`), Stat('user', () => user.name)), Profile(user), LiveProfile(() => user), div( row, button('Add item', { onClick: () => { cart++; commit() } }), button('Rename user', { onClick: () => { user = { ...user, name: user.name === 'Ada' ? 'Grace' : 'Ada' }; commit() }, }), button('Toggle plan', { onClick: () => { user = { ...user, plan: user.plan === 'Pro' ? 'Free' : 'Pro' }; commit() }, }), ), p('The mount count never moves: update() re-runs the functions and patches text. The static card keeps the values it was built with, by design.'), )