(() => {
const init = () => {
model.init()
view.init()
Controal.init()
}
const model = {
data: {
one: 1,
two: 2,
total: 3,
symbol: '+'
},
init: () => {
const _this = model
for (let key in _this.data) {
Object.defineProperty(_this, key, {
get: () => {
return _this.data[key]
},
set: (newValue) => {
_this.data[key] = newValue
view.init({
[key]: newValue
})
}
})
}
}
}
const Controal = {
init: function() {
const allInputValues = document.querySelectorAll('input')
const allSymbols = document.querySelectorAll('.symbols')
for (let i = 0; i < allInputValues.length; i++) {
const intItem = allInputValues[i]
intItem.addEventListener('input', this.handleInput, false)
}
for (let i = 0; i < allSymbols.length; i++) {
const symItem = allSymbols[i]
symItem.addEventListener('click', this.handleClick, false)
}
},
handleInput: (e) => {
const tar = e.target,
value = Number(tar.value),
className = tar.className,
targetName = className.split(' ')[1]
model[targetName] = value
model.total = eval('model.one' + model.symbol + 'model.two')
},
handleClick: (e) => {
const tar = e.target,
className = tar.className.split(' ')[1].slice(0, -1),
value = tar.textContent;
model[className] = value
model.total = eval('model.one' + model.symbol + 'model.two')
}
}
const view = {
el: '#app',
template: `
<div class="content">
<p>
<span class="cal one">{{ one }}</span>
<span class="cal symbol">{{ symbol }}</span>
<span class="cal two">{{ two }}</span>=
<span class="cal total">{{ total }}</span>
</p>
<p>
one<input type="text" class="int one"></input>
two<input type="text" class="int two"></input>
</p>
<p>
<span class="cal symbols">+</span>
<span class="cal symbols">-</span>
<span class="cal symbols">*</span>
<span class="cal symbols">/</span>
</p>
</div>
`,
init: function (mutiData) {
if (!mutiData) {
this.template = this.template.replace(/\{\{(.*?)\}\}/g, function (node, key) {
return model[key.trim()]
})
const container = document.createElement('div')
container.innerHTML = this.template
document.querySelector(this.el).appendChild(container)
} else {
for (let key in mutiData) {
const targetElement = document.querySelector(`.${key}`)
targetElement.textContent = mutiData[key]
}
}
}
}
init()
})()
MVC 简单模式 实现加减乘除
最新推荐文章于 2022-11-03 21:30:25 发布