Skip to content

Instantly share code, notes, and snippets.

@LeeXun
Created November 9, 2017 16:58
Show Gist options
  • Save LeeXun/a6ceeebf54ddf4dcf8c1985486508335 to your computer and use it in GitHub Desktop.
Save LeeXun/a6ceeebf54ddf4dcf8c1985486508335 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Two way binding</title>
<style>
#app {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="app">
<div class="row">
<input type="text" id="input" xun-value="">
</div>
<div class="row">
<div class="dom"></div>
</div>
<div class="row">
<div class="dom"></div>
</div>
<div class="row">
<div class="dom"></div>
</div>
</div>
<script>
var state = {
setState(key, v) {
this["_"+key] = v
this[key] = v
console.log(this[key])
},
_x: '',
twoWayDOM: {
componentNames: [
'#input',
'.dom'
]
},
set x(v) {
this.twoWayDOM.componentNames.forEach(selector => {
if(selector[0] == '.') {
var nodeList = document.querySelectorAll(selector)
nodeList.forEach(node => {
if(node.tagName == 'INPUT') {
node.value = v
}
if(node.tagName == 'DIV') {
node.innerHTML = v
}
})
} else {
var node = document.querySelector(selector)
if(node.tagName == 'INPUT') {
node.value = v
}
if(node.tagName == 'DIV') {
node.innerHTML = v
}
}
})
},
get x() {
return this._x
}
}
let input = document.querySelector('#input')
input.addEventListener('input', (inputEvent) => {
console.log(inputEvent)
if(inputEvent.inputType == 'insertText') {
state.setState('x', state.x + inputEvent.data)
} else if (inputEvent.inputType == 'deleteContentBackward') {
state.setState('x', state.x.slice(0, -1))
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment