dynamic-componet
Minimal functional components for websites. This library is a thin wrapper around virtual-dom
.
Motivation
Dynamic Component is a module that simplifies adding dynamic behaviour to HTML pages with JavaScript. It is common for developers to use jQuery to add dynamic elements like carousels or accordions, and for those simple cases, the recommended tool is jQuery. However, for more complicated scenarios, dynamic-component aims to provide an expressive and powerful way to dynamically manipulate HTML by leveraging the virtual-dom library and stateful change propagation.
This library also uses the dom-delegator package to handle global DOM event delegation to ensure virtual-dom's EvHooks work as expected.
References:
Example usage
// a simple dynamic component that queries giphy for a random gif// when a button is clicked // import dynamic-componet and set up the scopevar dc = ;var $ = ;// create the state mutator that will dynamically update the DOMvar stateMutator = dc;// query the DOM for the element to contain the dynamic behaviourvar element = document; // set up the render function// this uses virtual-dom's virtual-hyperscript function, h { var h = dch; return ;} // bind the state and the render function to the DOMdc;
API
The following table describes the various functions that are part of this package. Functions prefixed by dc
are part of the object exported from dynamic-component
directly, while those prefixed by stateMutator
represent the functions in the object returned by dc.createState
.
Function | Type Signature | Description |
---|---|---|
dc.h |
See virtual-hyperscript | The virtual-hyperscript function packaged with virtual-dom . |
dc.createState |
initialState :: Optional Object -> stateMutator :: Object |
Creates a state mutator. |
dc.bind |
stateMutator :: Object -> render :: (state :: Object -> vtree :: VTree) -> element :: HTMLElement -> undefined |
Binds a state mutator and render function to an element returned from document.querySelector . |
stateMutator.get |
-> state :: Object | Returns a deep copy of the state object. |
stateMutator.set |
newStateValues :: Object -> silent=false :: Boolean -> shouldGet=false :: Boolean -> state :: Object OR undefined |
Update the state, by performing a shallow assign of newStateValues to the original state object. Optionally operates silently without triggering a re-render, and optionally returns a deep copy of the new state. |
stateMutator.subscribe |
handler :: (state :: Object -> undefined) -> unsubscribe :: (-> undefined) |
Subscribe to state changes persisted with stateMutator.set . Returns a function that unsubscribes the subscription. |
Links
Author
Dhruv Dang
hi@dhruv.io
dhruv.io