@lfarssi/lfarssijs
v1.0.2
Published
just a mini framework based on react and vue js
Readme
Virtual DOM Implementation Guide
Overview
This is a minimal Virtual DOM implementation that demonstrates the core concepts used by modern frameworks like React and Vue. The Virtual DOM is a JavaScript representation of the actual DOM that allows for efficient updates through diffing and patching.
Core Components
1. VNode Class
export class Vnode {
constructor(tag, attrs = {}, children = []) {
this.tag = tag;
this.attrs = attrs;
this.children = children;
}
}The VNode represents a virtual DOM element with:
tag: HTML tag name (e.g., 'div', 'span')attrs: Object containing attributes (e.g., {id: 'myId', class: 'myClass'})children: Array of child VNodes or text strings
2. Render Function
Converts a VNode into an actual DOM element recursively. It creates the element, sets attributes, and appends all children.
3. Mount Function
Takes a VNode and appends it to a target DOM element, essentially the initial render.
4. Diff Function
Compares two VNode trees and returns a patch object describing the differences:
REMOVE: Node should be removedREPLACE: Node should be completely replacedUPDATE: Node should be updated (attributes or children changed)
5. Patch Function
Applies the patches generated by Diff to the actual DOM, making minimal changes for optimal performance.
How It Works
- Create VNodes: Build a virtual representation of your UI
- Initial Render: Mount the VNode tree to the DOM
- State Changes: Create a new VNode tree representing the new state
- Diff: Compare old and new VNode trees to find differences
- Patch: Apply only the necessary changes to the real DOM
Example Usage
import { Vnode, Mount } from './vdom.js';
// Create initial virtual DOM
const oldVnode = new Vnode('div', { id: 'app' }, [
new Vnode('h1', {}, ['Hello World']),
new Vnode('p', {}, ['Count: 0'])
]);
// Mount to actual DOM
const container = document.getElementById('root');
Mount(oldVnode, container);
// Simulate state change
const newVnode = new Vnode('div', { id: 'app' }, [
new Vnode('h1', {}, ['Hello Virtual DOM']),
new Vnode('p', {}, ['Count: 1']),
new Vnode('button', { onclick: 'increment()' }, ['Click me'])
]);
// Find differences and patch
const patches = Diff(oldVnode, newVnode);
Patch(container, patches);Key Benefits
- Performance: Only updates parts of the DOM that actually changed
- Predictability: Declarative UI updates make code easier to reason about
- Batching: Multiple changes can be batched together for efficient updates
Limitations of This Implementation
- No event handling optimization
- No component lifecycle management
- No state management
- Basic attribute handling (doesn't handle special cases like
styleobjects)
This implementation serves as an educational example of how Virtual DOM works under the hood in modern frameworks.
