HyperApp构建前端应用的 JavaScript 库
HyperApp 是一个用于构建前端应用的 JavaScript 库,体积十分轻量,仅 1KB。具有以下特性:
-
声明式:HyperApp 的设计基于 Elm Architecture。使用函数式范例创建可扩展的基于浏览器的应用程序。你不必学习一种新的语言。
-
自定义标签:使用自定义标签构建复杂的用户界面。自定义标签是无状态的,易于调试。
-
Batteries-included:开箱即用,HyperApp 具有类 Elm 的状态管理和虚拟 DOM 引擎;但它仍然只有 1kb 的大小,没有依赖关系。
示例:Hello World
Hello World Try it online app({ state: 0, view: (state, actions) => ( <main> <h1>{state}</h1> <button onclick={actions.add}>+</button> <button onclick={actions.sub}>-</button> </main> ), actions: { add: state => state + 1, sub: state => state - 1 } })
简介
安装
npm i -S hyperapp
在 Node.js 中
import { h, app } from "hyperapp"
在浏览器中通过 CDN
const { h, app } = hyperapp
示例
Hello world
app({ model: "Hi.", view: model => html`<h1>${model}</h1>` })
Counter
app({ model: 0, update: { add: model => model + 1, sub: model => model - 1 }, view: (model, msg) => html` <div> <button onclick=${msg.add}>+</button> <h1>${model}</h1> <button onclick=${msg.sub} disabled=${model <= 0}>-</button> </div>` })
Input
app({ model: "", update: { text: (_, value) => value }, view: (model, msg) => html` <div> <h1>Hi${model ? " " + model : ""}.</h1> <input oninput=${e => msg.text(e.target.value)} /> </div>` })
Drag & Drop
const model = { dragging: false, position: { x: 0, y: 0, offsetX: 0, offsetY: 0 } } const view = (model, msg) => html` <div onmousedown=${e => msg.drag({ position: { x: e.pageX, y: e.pageY, offsetX: e.offsetX, offsetY: e.offsetY } })} style=${{ userSelect: "none", cursor: "move", position: "absolute", padding: "10px", left: `${model.position.x - model.position.offsetX}px`, top: `${model.position.y - model.position.offsetY}px`, backgroundColor: model.dragging ? "gold" : "deepskyblue" }} >Drag Me! </div>` const update = { drop: model => ({ dragging: false }), drag: (model, { position }) => ({ dragging: true, position }), move: (model, { x, y }) => model.dragging ? ({ position: { ...model.position, x, y } }) : model } const subs = [ (_, msg) => addEventListener("mouseup", msg.drop), (_, msg) => addEventListener("mousemove", e => msg.move({ x: e.pageX, y: e.pageY })) ] app({ model, view, update, subs })
评论