Skip to content

Instantly share code, notes, and snippets.

@uchcode
Last active July 21, 2016 12:50
Show Gist options
  • Save uchcode/3ec7b88f49023cb354f36b2c044e8537 to your computer and use it in GitHub Desktop.
Save uchcode/3ec7b88f49023cb354f36b2c044e8537 to your computer and use it in GitHub Desktop.
ビューの基本と応用

ビューの基本

出力の例

document.getElementById('contents').innerHTML += '<p>hello again</p>'

アルゴリズムのサブルーチン化

function render(id, html) {
  document.getElementById(id).innerHTML += html
}

render('contents', '<p>hello</p>')

データ処理のパターン化

function render(id, html) {
  document.getElementById(id).innerHTML += html
}

function paragraph(data) {
  return `<p>${data}</p>`
}

render('contents', paragraph('hello'))

サブルーチンとパターンの統合

class View {
  render(id, html) {
    document.getElementById(id).innerHTML += html
  }
  paragraph(data) {
    return `<p>${data}</p>`
  }
  output(id, data) {
    this.render(id, this.paragraph(data))
  }
}

let v = new View()
v.output('contents', 'hello')

パターンを加える

class View {
  render(id, html) {
    document.getElementById(id).innerHTML += html
  }
  h1(data) {
    return `<h1>${data}</h1>`
  }
  paragraph(data) {
    return `<p>${data}</p>`
  }
  output(id, pattern, data) {
    this.render(id, this[pattern](data))
  }
}

let v = new View()
v.output('header', 'h1', 'hello')
v.output('contents', 'paragraph', 'hello')

ビューの応用

ビューのみ使用

class View {
  render(id, html) {
    document.getElementById(id).innerHTML += html
  }
  paragraph(data) {
    return `<p>${data}</p>`
  }
  output(id, data) {
    this.render(id, this.paragraph(data))
  }
}

class Application {
  constructor(id, view) {
    this.id = id
    this.view = view
  }
  greet(greeting) {
    this.view.output(this.id, greeting)
  }
  initialGreet() {
    this.greet('hello')
  }
  finalGreet() {
    this.greet('good bye')
  }
}

let a = new Application( 'contents', new View() )
a.initialGreet()
a.finalGreet()

モデルとビューの組み合わせ

class Model {
  constructor(initial, final) {
    this.initialGreeting = initial || 'hello'
    this.finalGreeting = final || 'good bye'
  }
}

class View {
  render(id, html) {
    document.getElementById(id).innerHTML += html
  }
  paragraph(data) {
    return `<p>${data}</p>`
  }
  output(id, data) {
    this.render(id, this.paragraph(data))
  }
}

class Application {
  constructor(id, view, model) {
    this.id = id
    this.view = view
    this.model = model
  }
  greet(greeting) {
    this.view.output(this.id, greeting)
  }
  initialGreet() {
    this.greet(this.model.initialGreeting)
  }
  finalGreet() {
    this.greet(this.model.finalGreeting)
  }
}

let a = new Application( 'contents', new View(), new Model() )
a.initialGreet()
a.finalGreet()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment