LoginSignup
8
6

More than 5 years have passed since last update.

ブラウザ上の MVC的な分割を Node Stream API で行う

Posted at

Node Streamをブラウザで動かす で、ブラウザ上でNode Streamが使えることがわかりました。

典型的なMVC分割に使えることを示します。

概要

ボタンをクリックするとカウンターをインクリメントします。
out.gif

設計

  • ControllerStream ボタンのクリックイベントをStreamに変換する
  • ModelStream クリックイベントに応じて値を更新する
  • ViewStream 値をDOMに反映する

ソースコード

index.js
import {
  Writable,
  Readable,
  Transform
}
from 'stream'

const option = {
  objectMode: true
}

class ControllerStream extends Readable {
  constructor(id) {
    super(option)
    document.querySelector(`#${id}`).addEventListener('click', e => this.push(e))
  }
  _read() {}
}

class ModelStream extends Transform {
  constructor(initialValue) {
    super(option)

    this._value = initialValue
    this.push(this._value)
  }
  _transform(chunk, encoding, done) {
    this._value++;
    this.push(this._value)

    done()
  }
}

class ViewStream extends Writable {
  constructor(id) {
    super(option)
    this._element = document.querySelector(`#${id}`)
  }
  _write(chunk, encoding, callback) {
    this._element.innerHTML = chunk

    callback()
  }
}

new ControllerStream('button')
  .pipe(new ModelStream(0))
  .pipe(new ViewStream('count'))
index.html
<body>
  <button id="button">+</button>
  <span id="count"></span>
  <script src="bundle.js"></script>
</body>

準備

npm install browserify babelify stream-browserify

ビルド

node_modules/browserify/bin/cmd.js index.js -t babelify > bundle.js
8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6