创建高效的HTML元素 - nanocomponent

2017-01-05      177      JavaScript
项目简介

nanocomponent

封装原生DOM库适配DOM定义算法,创建高效的HTML元素

使用方法

// Implementer API
var Nanocomponent = require('nanocomponent')
var html = require('bel')

function MyButton () {
  if (!(this instanceof MyButton)) return new MyButton()
  this._color = null
  Nanocomponent.call(this)
}
MyButton.prototype = Object.create(Nanocomponent.prototype)

MyButton.prototype._render = function (color) {
  this._color = color
  if (!this._element) {
    // initial render
    return html`
      <button style="background-color: ${color}">
        Click Me
      </button>
    `
  } else {
    // mutate this._element
    this._element.style.backgroundColor = color
  }
}

MyButton.prototype._update = function (newColor) {
  return newColor !== this._color
}
// Consumer API
var MyButton = require('./my-button.js')
var myButton = MyButton()
document.body.appendChild(myButton.render())

实现高级API

var MyComponent = require('./my-component')
var myComponent = MyComponent()

myComponent.on('render', function () {
  console.log('rendered')
})

myComponent.on('load', function () {
  console.log('loaded on DOM')
})

myComponent.on('unload', function () {
  console.log('removed from DOM')
})

document.body.appendChild(myComponent.render())

安装

$ npm install nanocomponent