Application( Model, View ) Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>reactive</title>
</head>
<body>
<div id="contents"></div>
</body>
<script>
'use strict'
class Model {
constructor() {
this.number = 0
}
square() {
return Number( Math.pow(this.number, 2) )
}
}
class View {
constructor() {
this.numberElm = document.createElement('input')
this.numberElm.value = 0
this.resultElm = document.createElement('span')
this.resultElm.innerHTML = 0
}
get number() {
return Number(this.numberElm.value)
}
set number(v) {
this.numberElm.value = Number(v)
}
get result() {
return Number(this.resultElm.innerHTML)
}
set result(v) {
this.resultElm.innerHTML = Number(v)
}
connect(target, type, listener) {
this[target].addEventListener(type, listener)
}
render(id) {
let element = id ? document.getElementById(id) : document.body
element.appendChild(this.numberElm)
element.appendChild(this.resultElm)
}
}
class Application {
constructor() {
this.model = new Model()
this.view = new View()
}
get number() {
return this.view.number
}
set number(v) {
this.model.number = Number(v)
this.view.number = v
}
get result() {
return this.view.result
}
set result(v) {
this.view.result = v
}
render(id) {
let self = this
let { view } = this
view.connect('numberElm', 'change', () => {
self.calc()
})
view.render(id)
}
calc() {
let { model } = this
model.number = this.number
this.result = model.square()
}
}
let a = new Application()
a.render('contents')
a.number = 9
a.calc()
console.log( a.model.number, a.model.result )
console.log( a.view.number, a.view.result )
</script>
</html>