使用 Hyperscript

Hyperscript 指的是使用 JavaScript 来创建 Hypertext(超文本),一个比较经典 Hyperscript 实现是hyperhype/hyperscript。与 ejs,JSX,jade 等模板语言(template language)不同,Hyperscript 通过函数来创建 DOM 元素:

var h = require('hyperscript')
h('div#page',
  h('div#header',
    h('h1.classy', 'h', { style: {'background-color': '#22f'} })),
  h('div#menu', { style: {'background-color': '#2f2'} },
    h('ul',
      h('li', 'one'),
      h('li', 'two'),
      h('li', 'three'))),
    h('h2', 'content title',  { style: {'background-color': '#f22'} }),
    h('p',
      "so it's just like a templating engine,\n",
      "but easy to use inline with javascript\n"),
    h('p',
      "the intention is for this to be used to create\n",
      "reusable, interactive html widgets. "))

在上一节的程序中,我们自定义一个 Hyperscript 函数来创建 DOM 元素:

function h(tagName, children) {
    return {
        tagName,
        children
    };
}

function main(sources) {
  const hover$ = sources.DOM.selectEvents('span', 'mouseover');
  return {
    DOM: hover$
      .startWith(null)
      .flatMapLatest(() =>
        Rx.Observable.timer(0, 1000)
          .map(i => h('H1', [h('SPAN', [`Seconds Elapsed ${i}`])]))
      ),
    Log: Rx.Observable.timer(0, 2000)
      .map(i => 2 * i)
  };
}

更形象地,我们为不同的 HTML 标签创建不同的 Hyperscript 函数:

function h(tagName, children) {
    return {
        tagName,
        children
    };
}

function h1(children) {
    return h('H1', children);
}

function span(children) {
    return h('SPAN', children);
}

function main(sources) {
  const hover$ = sources.DOM.selectEvents('span', 'mouseover');
  return {
    DOM: hover$
      .startWith(null)
      .flatMapLatest(() =>
        Rx.Observable.timer(0, 1000)
          .map(i => h1([span([`Seconds Elapsed ${i}`])]))
      ),
    Log: Rx.Observable.timer(0, 2000)
      .map(i => 2 * i)
  };
}

在 jsbin 上看下效果:

查看示例

results matching ""

    No results matching ""