【连载】Hyperapp.js入门系列(3):API参考
0 83

在这里,我们将结合示例介绍如何使用Hyperapp的模块和函数。

Hyperapp主要提供了两大功能:

  • h函数
    生成虚拟DOM的函数
  • app函数
    使用Hyperapp执行应用程序的功能

h()

返回虚拟DOM的函数。 这里的虚拟DOM指的是以JavaScript对象表现的嵌套DOM树。

  • name {String}
    「div」等HTML里的标签名
  • props {Object}
    插入元素的属性值
  • children {String | Array}
    子元素
h("a", { href: "#" }, "next page")
// return object
// {
//   name: 'a',
//   props: {
//     href: '#'
//   },
//   children: 'next page'
// }

app()

启动Hyperapp应用程序

app(state, actions, view, container

state

管理应用程序状态的对象。 必需是一个纯JS对象。

view

返回虚拟DOM的函数。 以state和actions为参数

const state = {
  on: true
}
const actions = {
  toggle: () => state => ({ on: !state.on })
}
const view = (state, actions) => (
  <button onclick={actions.toggle}>{state.on.toString()}</button>
)
app(state, actions, view, document.body)

actions

定义应用程序行为的函数集合。 actions通常用于更新state。 其返回值通常是一个新的state

const actions = {
  setValue: value => ({ value }),
  addValue: value => state => ({ value: state.value + value }),
  addValueLater: value => (state, actions) => {
    setTimeout(() => {
      actions.addValue(value)
    }, 1000)
  }
}
  • data
    actions处理(模型更新)所需的数据
  • state
    当前state
  • actions
    应用程序的原始actions
const state = { count: 0 }
const actions = {
  sub: () => state => state - 1,
  add: () => state => state + 1
}
const view = (state, actions) => (
  <div>
    <h1>{state.count}</h1>
    <button onclick={actions.sub} disabled={state.count <= 0}>
      -
    </button>
    <button onclick={actions.add}>+</button>
  </div>
)
app(state, actions, view, document.body)

全局事件

app函数返回的对象包含关联state的原始actions。 与传递给view的ctions相同,调用ctions时state会被更新。

const state = { x: 0, y: 0 }
const actions = {
  move: () => ({ x, y }) => ({ x, y })
}
const view = state => <h1>{state.x + ", " + state.y}</h1>
const MyApp = app(state, actions, view, document.body)
addEventListener("mousemove", e =>
  MyApp.move({
    x: e.clientX,
    y: e.clientY
  })
)

生命周期方法

虚拟DOM提供了一些生命周期相关的事件

  • oncreate
    Elment被加进DOM
  • onupdate
    Element被更新
  • onremove
    在Element从DOM中移除
  • ondestroy
    Element被释放
const node = document.createElement("div")
const editor = CodeMirror(node)
const Editor = options => {
  const setOptions = options =>
    Object.keys(options).forEach(key => editor.setOption(key, options[key]))
  const oncreate = elm => {
    setOptions(options)
    elm.appendChild(node)
  }
  const onupdate = _ => setOptions(options)
  return <div oncreate={oncreate} onupdate={onupdate} />
}
0 83
() 全部评论
所有回复 (0)

推荐总结

  • Hyperapp 170 0 1 发布
    简介

    Hyperapp是一个用于开发Web应用程序前端(主要是View部分)的现代JavaScript库,它的大小仅有1.3kB,并且非常容易上手。

    Hyperapp的架构借鉴了React、Redux以及Elm,支持JSX同时也提供了一些JSX的替代方案,比如h函数(Hyperapp的首字母)、hyperapp/html、hyperx、t7。

    Hyperapp的初衷就是以尽量少的代码做尽量多的事。但Hyperapp虽小,仍然包含了状态管理、虚拟DOM引擎,所有这些都是独立实现,不依赖于任何第三方库的。

    导入使用CDN不指定版本 <script src="https://unpkg.com/hyperapp"></script> 指定版本 <script src="https://unpkg.com/hyperapp@1.0.1"></script> HelloWord

    Hyperapp可以使用JSX表示法,以及基于ES6字符串模板的Hyperx表示法。下面两种写法的代码都准备好了,您可以根据自己的喜好自由选用。

    使用JSX<body> <script src="https://unpkg.com/hyperapp@1.0.1"></script> <script src="https://unpkg.com/babel-standalone"></script> <script type="text/babel"> const { h, app } = hyperapp /** @jsx h */ const state = { greeting: "Hello,world" } const actions = {} const view = state => <h1 id="title">{state.greeting}</h1> app(state, actions, view, document.body) </script> </body> 使用Hyperx<body> <script src="https://unpkg.com/hyperapp@1.0.1"></script> <script src="https://wzrd.in/standalone/hyperx"></script> <script> const { h, app } = hyperapp const html = hyperx(h) const state = { greeting: "Hello,world" } const actions = {} const view = state => html`<h1 id="title">${state.greeting}</h1>` app(state, actions, view, document.body) </script> </body>

    浏览器中会发生什么呢?

    浏览器通过CDN下载了Hyperx和JSX,编译并渲染<script>部分,最终在页面上显示了“hello,world”。

  • Hyperapp 79 0 1 发布

    Web应用程序的开发环境包括三个要素:

    Package Manager(例如:npm,yarn)Complier(例如:babel,Buble)Bundler(例如:Webpack, Browserify, Rollup)

    之所以需要这些,是因为要编译用JSX/ Hyperx编写的源代码,当编译时,它成为生成虚拟DOM的函数,称为Hyperapp的h函数。

    编译前(JSX/Hyperx)

    <h1 id="test">Hi.</h1>

    编译后

    h("h1", { id: "test" }, "Hi.")

    JSX开发环境

    JSX采用与XML同样的记法,通过JSX您可以将HTML(模板)和JavaScript(处理)混合在一个文件中。
    要使用JSX,您需要如上所述进行编译。 您必须将JSX转换为h函数,将其打包为一个js文件,然后进行发布。

    如果是使用Browserify

    安装必要的模块

    npm i -S hyperapp npm i -D babel-plugin-transform-react-jsx babel-preset-es2015 babelify browserify bundle-collapser uglifyify uglifyjs

    准备.babelrc文件

    { "presets": ["es2015"], "plugins": [ [ "transform-react-jsx", { "pragma": "h" } ] ] }

    编译打包

    browserify \ -t babelify \ -g uglifyify \ -p bundle-collapser/plugin index.js | uglifyjs > bundle.js

    如果是使用Webpack

    安装必要的模块

    npm i -S hyperapp npm i -D babel-plugin-transform-react-jsx babel-preset-es2015 babelify browserify bundle-collapser uglifyify uglifyjs

    准备.babelrc文件

    { "presets": ["es2015"], "plugins": [ [ "transform-react-jsx", { "pragma": "h" } ] ] }

    准备webpack.config.js文件

    module.exports = { entry: "./index.js", output: { filename: "bundle.js" }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" } ] } }

    编译打包

    webpack -p

    如果是使用Rollup

    安装必要的模块

    npm i -S hyperapp npm i -D rollup rollup-plugin-babel rollup-plugin-node-resolve rollup-plugin-uglify babel-preset-es2015-rollup babel-plugin-transform-react-jsx

    准备rollup.config.js文件

    import babel from "rollup-plugin-babel" import resolve from "rollup-plugin-node-resolve" import uglify from "rollup-plugin-uglify" export default { plugins: [ babel({ babelrc: false, presets: ["es2015-rollup"], plugins: [["transform-react-jsx", { pragma: "h" }]] }), resolve({ jsnext: true }), uglify() ] }

    编译打包

    rollup -cf iife -i index.js -o bundle.js

    Hyperx开发環境

    编辑中(基本与JSX开发环境相似,仅一些地方安装的模块有些不同)

热门总结

  • HTML5 17041 0 1 发布

    本目录收录的是电子邮件相关的应用软件。


    定义

    电子邮件(Email)又称电子邮箱,简称电邮,是指一种由一寄件人将数字信息发送给一个人或多个人的信息交换方式,目的是达成发信人和收信人之间的信息交互。

    电子邮件系统是以存储与转发的模型为基础,邮件服务器接受、转发、提交及存储邮件。寄信人、收信人及他们的电脑都不用同时在线。寄信人和收信人只需在寄信或收信时简短的连接到邮件服务器即可。

    范围

    本目录收录的软件仅限于以电子邮件为主要功能(或之一)的应用软件。

    列表

    本目录收录了以下软件:

     RainLoop

    简单的、 现代的 & 快速、 基于 WEB 的电子邮件客户端。

    以下是 RainLoop 各相关链接及授权信息的介绍:

    官网(HP)
    https://www.rainloop.net/源代码(Source)
    https://github.com/RainLoop/rainloop-webmail授权(License)
    AGPL 3.0范例(Example)
    https://mail.rainloop.net/#/mailbox/INBOX

  • HTML5 16632 0 1 发布

    本目录收录的是即时通信相关的应用软件。

     定义

    即时通信(Instant Messaging,IM)是一种通过网络进行实时通信的系统,允许两人或多人使用网络即时的传递文字消息、文件、语音与视频交流。

    即时通信不同于电子邮件在于它的交谈是即时(实时)的。大部分的即时通信服务提供了状态信息的特性──显示联系人名单,联系人是否在在线与能否与联系人交谈等等。

    范围

    本目录收录的软件仅限于以即时通信为主要功能(或之一)的应用软件。

    列表

    本目录收录了以下软件:

    CandyConverse.jsKaiwaRocket.Chat

    Candy

    Candy是一个支持XMPP协议的多用户即时聊天客户端软件。

    以下是 Candy 各相关链接及授权信息的介绍:

    官网(HP)
    http://candy-chat.github.io/candy源代码(Source)
    https://github.com/candy-chat/candy授权(License)
    MIT范例(Example)

    Converse.js

    Converse.js是一个支持XMPP/JABB的多用户即时聊天客户端软件。

    以下是 Converse.js各相关链接及授权信息的介绍:

    官网(HP)
    http://conversejs.org源代码(Source)
    https://github.com/jcbrand/converse.js授权(License)
    MPL范例(Example)
    https://conversejs.org/demo/anonymous.html

    Kaiwa

    Kaiwa 是一个支持XMPP的即时聊天客户端软件。

    以下是 Kaiwa 各相关链接及授权信息的介绍:

    官网(HP)
    http://getkaiwa.com源代码(Source)
    https://github.com/digicoop/kaiwa授权(License)
    MPL范例(Example)

    Rocket.Chat

    WebChat平台。

    以下是 Rocket.Chat 各相关链接及授权信息的介绍:

    官网(HP)
    https://rocket.chat/源代码(Source)
    https://github.com/RocketChat/Rocket.Chat授权(License)
    MIT范例(Example)
    https://demo.rocket.chat/home

  • HTML5 16264 0 1 发布

    本目录收录的是流程图相关的应用软件。


    定义

    流程图(Flowchart Diagram)是表示算法、工作流或流程的一种框图表示,它以不同类型的框代表不同种类的步骤,每两个步骤之间则以箭头连接。

    流程图大致可以分为以下四种类型:

    文件流程图数据流程图系统流程图程序流程图范围

    本目录收录的软件仅限于以流程图实现为主要功能(或之一)的应用软件。

    列表

    本目录收录了以下软件:

    Diagramo

    Diagramo是一个流程图模型编辑工具

    以下是Diagramo各相关链接及授权信息的介绍:

    官网(HP)
    http://diagramo.com源代码(Source)
    https://github.com/ssshow16/diagramo授权(License)
    GPL范例(Example)
    http://diagramo.com/editor/editor.php

  • HTML5 13423 0 1 发布

    ERD

    本目录收录的是ERD模型相关的应用软件。

    定义

    ERD(Entity-relationship Diagram,实体关系图)是概念数据模型的高层描述所使用的数据模型或模式图。

    ERD由实体和实体之间的关系定义而成,实体(Entity)表示一个离散对象,可以被(粗略地)认为是名词,如人、交易等。关系(Relationship)描述了两个或更多实体相互如何关联,联系可以被(粗略地)认为是动词。

    范围

    本目录收录的软件仅限于以ERD模型实现为主要功能(或之一)的应用软件。

    列表

    本目录收录了以下软件:

    WWWSqlDesigner

    WWWSqlDesigner是一个ER图形工具,允许用户创建数据库设计,可以保存/加载并导出到SQL脚本。 支持各种数据库和语言,能够导入现有的数据库设计。

    以下是WWWSqlDesigner各相关链接及授权信息的介绍:

    官网(HP)
    https://github.com/ondras/wwwsqldesigner源代码(Source)
    https://github.com/ondras/wwwsqldesigner授权(License)
    BSD范例(Example)
    http://ondras.zarovi.cz/sql/demo/?keyword=default

  • PHP 9365 0 1 发布

    Bootstrap3是一个高度可定制的基于Bootstrap的DokuWiki模板,具有响应性,适用于所有设备(移动设备,平板电脑,台式机等)。

    功能和特点HTML5和CSS3基于Bootstrap 3.xGlyphicons 和 FontAwesome图标AnchorJS支持可高度定制丰富的HTML和DokuWiki钩子侧边栏支持(左侧和右侧)主题切换器插件统合Bootstrap Wrapper PluginDiagram PluginDiscussion PluginEdittable PluginExplain PluginInlinetoc PluginLinkback PluginMove PluginOverlay PluginPublish PluginRack PluginTagging PluginTags PluginTranslation PluginUser Home-Page PluginWrap Plugin - TabsTplInc Plugin设定主题项目名项目说明值类型缺省值可选值bootstrapThemeBootstrap主题multichoicedefaultdefault
    optional
    custom
    bootswatchbootswatchTheme从Bootswatch.com选择主题multichoiceyeticerulean
    cosmo
    cyborg
    darkly
    flatly
    journal
    lumen
    paper
    readable
    sandstone
    simplex
    solar
    slate
    spacelab
    superhero
    united
    yeticustomTheme插入自定义主题的URLstringnullshowThemeSwitcher在导航栏中显示Bootswatch.com主题切换器onoff0hideInThemeSwitcher在主题切换器中隐藏主题multicheckboxnullcerulean
    cosmo
    cyborg
    darkly
    flatly
    journal
    lumen
    paper
    readable
    sandstone
    simplex
    solar
    slate
    spacelab
    superhero
    united
    yetithemeByNamespace按名字空间指定主题onoff0侧边栏项目名项目说明值类型缺省值sidebarPositionDokuWiki Sidebar position (left or right)multichoiceleftleft
    rightrightSidebarThe Right Sidebar page name, empty field disables the right sidebar.
    The Right Sidebar is displayed only when the default DokuWiki sidebar is enabled and is on the left position (see the sidebarPosition configuration). If do you want only the DokuWiki sidebar on right position, set the sidebarPosition configuration with right valuestringrightsidebarleftSidebarGridLeft sidebar grid classes col-{xs,sm,md,lg}-x (see Bootstrap Grids documentation)stringcol-sm-3 col-md-2rightSidebarGridRight sidebar grid classes col-{xs,sm,md,lg}-x (see Bootstrap Grids documentation)stringcol-sm-3 col-md-2sidebarOnNavbarDisplay the sidebar contents inside the navbar (useful on mobile/tablet devices)onoff0sidebarShowPageTitleDisplay Sidebar page titleonoff1导航栏项目名项目说明值类型缺省值inverseNavbarInverse navbaronoff0fixedTopNavbarFix navbar to toponoff0showTranslationDisplay translation toolbar (require Translation Plugin)onoff0showToolsDisplay Tools in navbarmultichoicealwaysnever
    logged
    alwaysshowHomePageLinkDisplay Home-Page link in navbaronoff0homePageURLUse custom URL for home-page linksstringnullshowUserHomeLinkDisplay User Home-Page link in navbaronoff1hideLoginLinkHide the login button in navbar. This option is useful in “read-only” DokuWiki installations (eg. blog, personal website)onoff0showEditBtnDisplay edit button in navbarmultichoicenevernever
    logged
    alwaysindividualToolsSplit the Tools in individual menu in navbaronoff0showIndividualToolEnable/Disable individual tool in navbarmulticheckboxsite,pageuser
    site
    pageshowSearchFormDisplay Search form in navbarmultichoicealwaysnever
    logged
    alwaysshowAdminMenuDisplay Administration menuonoff0useLegacyNavbarUse legacy and deprecated navbar.html hook (consider in the future to use the :navbar hook)onoff0showNavbarDisplay navbar hookmultichoicealwayslogged
    alwaysnavbarLabelsShow/Hide individual labelmulticheckboxlogin,registerlogin
    register
    admin
    tools
    user
    site
    page
    themes
    expand
    profileshowAddNewPageEnable the Add New Page plugin in navbar (require Add New Page Plugin)multichoicenevernever
    logged
    alwaysnotifyExtensionsUpdateNotify extensions update (for Admin users)onoff0Semantic项目名项目说明值类型缺省值semanticEnable semantic dataonoff1schemaOrgTypeSchema.org type (Article, NewsArticle, TechArticle, BlogPosting, Recipe)multichoiceArticleArticle
    NewsArticle
    TechArticle
    BlogPosting
    RecipeshowSemanticPopupDisplay a popup with an extract of the page when the user hover on wikilink (require Semantic Plugin)onoff0布局项目名项目说明值类型Default ValuefluidContainerEnable the fluid container (full-width of page)onoff0fluidContainerBtnDisplay a button in navbar to expand containeronoff0pageOnPanelEnable the panel around the pageonoff1tableFullWidthEnable 100% full table width (Bootstrap default)onoff1tableStyleTable stylemulticheckboxstriped,condensed,responsivestriped
    bordered
    hover
    condensed
    responsiveshowLandingPageEnable the landing page (without a sidebar and the panel around the page)onoff0landingPagesLanding page name (insert a regex)regex(intro)showPageToolsEnable the DokuWiki-style Page Toolsmultichoicealwaysnever
    logged
    alwaysshowPageIdDisplay the DokuWiki page name (pageId) on toponoff1showBadgesShow badge buttons (DokuWiki, Donate, etc)onoff1showLoginOnFooterDisplay a “little” login link on footer. This option is useful when hideLoginLink is ononoff0showWikiInfoDisplay DokuWiki name, logo and tagline on footeronoff1文章目录 项目名项目说明值类型缺省值tocAffixAffix the TOC during page scrollingonoff1tocCollapseSubSectionsCollapse all sub-sections in TOC to save spaceonoff1tocCollapseOnScrollCollapse TOC during page scrollingonoff1tocCollapsedCollapse TOC on every pagesonoff0tocLayoutTOC layoutmultichoicedefaultdefault
    navbarg钩子HTML钩子

    所有文件必须位于模板目录(lib / tpl / bootstrap3 /)或conf /目录中。

    文件名插入到页面HTML中的位置meta.html <head>和</head>之间topheader.html紧接着<body>标签之后header.htmlAbove the upper blue bar, below the pagename and wiki titlenavbar.htmlDEPRECATED (see the note below) - Inside the navbar, use this to add additional links (e.g. <li><a href=“/foo”>Foo</a></li>)pageheader.htmlbreadcrumbs下面,页面实际内容的上方pagefooter.htmlAbove the lower blue bar, below the last changed Datefooter.html在页面的最后,位于</ body>标记之前sidebarheader.html边侧栏上方sidebarfooter.html边侧栏下方social.htmlBelow the header.html, use this to add a social buttons (eg. Google+, Twitter, LinkedIn, etc)rightsidebarheader.html右边侧栏上方rightsidebarfooter.html
    右边侧栏下方
    Dokuwiki钩子

    可以通过创建简单的DokuWiki“钩子”页面来自定义页面的各个部分。 bootstrap3模板会将这些钩子页面内容插入到页面的总体布局中。

    钩子页面名说明名字空间单位:sidebarThe sidebarYES:rightsidebarThe right-sidebarYES:navbarNavbar with sub-menusYES:pageheaderHeader of the Wiki articleYES:pagefooterFooter of the Wiki articleYES:footerFooter of the pageYES:cookie:bannerCookie-Law bannerNO:cookie:policyCookie-Law policyNO:helpHelp page for “Help Page Icon”YES:headerHeader of page below the navbarYES:topheaderTop Header of page (on top of navbar if fixedTopNavbar is off)YES

  • PHP 1189 0 1 发布
    CSS文件

    DokuWiki本体的CSS文件位于lib / styles目录中,不过DokuWiki本体仅定义了一些最基础的CSS,更多的CSS存在于模板和各个插件里面。
    所有CSS文件都是通过lib/exe /css.php程序获取的。该程序还处理缓存,模式替换,LESS预处理和优化,由tpl_metaheaders()函数调用。

    加载CSS的顺序如下: 在CSS中,如果为同一属性指定了不同的值,并且样式冲突,则稍后加载的样式将优先,并且属性值将被覆盖,因此首选样式是从后面开始。

    基本样式:lib /styles/*.css插件样式:lib / plugins / <插件名称> / *。css模板样式:在lib / tpl / <模板名称> /style.ini中定义用户样式:conf / user * .css

    如果要通过自定义CSS添加样式,则基本上应将其添加到用户样式(conf / user * .css)中。

    媒体类型

    样式表支持五种媒体类型:

    screen:用于显示器print:用于打印all:用于所有的媒体设备rtl:feed:外部链接Dokuwiki官方说明

  • HTML5 794 0 1 发布

    本目录收录的是电子表格相关的应用软件。

     定义

    电子表格(Spreadsheet),指的是类似于Micfosoft Excel的办公文档。它会显示由一系列行与列构成的网格,称为单元格,单元格之间可以合并成一个跨多行多列的大单元格。

    单元格内可以存放数值、计算式、或文本,单元格的边框和文本颜色字体通常可以个别设置。

    范围

    本目录收录的软件仅限于以电子表格为主要功能(或之一)的应用软件。

    列表

    本目录收录了以下软件:

    EtherCalc

    EtherCalc是一个实时多人协作的电子表格处理器,后台需NodeJS服务器

    以下是 EtherCalc各相关链接及授权信息的介绍:

    官网(HP)
    https://ethercalc.net/源代码(Source)
    https://github.com/audreyt/ethercalc授权(License)
    Apache 2范例(Example)

    https://ethercalc.net/

    截图

  • HTML5 410 0 1 发布

    本目录收录的是PDF相关的应用软件。

     定义

    PDF(Portable Document Format:便携式文档格式)是一种用独立于应用程序、硬件、操作系统的方式呈现文档的文件格式。

    每个PDF文件包含固定布局的平面文档的完整描述,包括文本、字形、图形及其他需要显示的信息,通常在任何设备和环境下都能获得同样的展现。

    范围

    本目录收录的软件仅限于以PDF为主要功能(或之一)的应用软件。

    列表

    本目录收录了以下软件:

    laddu-reader

    Laddu 是一个PDF阅读器,基于Mozilla的pdf.js。

    以下是 laddu-reader 各相关链接及授权信息的介绍:

    官网(HP)
    源代码(Source)
    https://github.com/iraycd/laddu-reader授权(License)
    MIT范例(Example)
    截图