Created
June 9, 2018 07:47
-
-
Save zenHeart/0bcb74759bd4c64bafef1420a420716a to your computer and use it in GitHub Desktop.
双向数据绑定
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<input id="dataInput" type="text" > | |
<p id="inputShow">{{inputValue}}</p> | |
<button onclick="mvvm.set()">重回初始值</button> | |
<script src="./mvvm.js"></script> | |
<script> | |
mvvm = new Render({ | |
inputEle:'#dataInput', | |
showEle:'#inputShow', | |
data:{ | |
inputValue:'demo' | |
} | |
}) | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Render { | |
/** | |
* | |
* @param {Object} opts 渲染函数的配置对象 | |
* @param {String} opts.showEle 视图元素的选择器 | |
* @param {String} opts.inputEle 输入触发的选择器 | |
* @param {Object} opts.data 绑定元素的数据 | |
* | |
*/ | |
constructor(opts) { | |
this.opts = opts; | |
this.defuault = JSON.parse(JSON.stringify(opts.data)); | |
this.showEle = document.querySelector(opts.showEle); | |
this.inputEle = document.querySelector(opts.inputEle); | |
this.key = null; | |
this.data = opts.data; | |
this.pattern = /^{{(\w+)}}/ | |
this.init(); | |
} | |
init() { | |
//绑定事件变化 | |
this.inputEle.oninput = this.onchange.bind(this); | |
this.show(); | |
this.set(); | |
} | |
onchange(events) { | |
let val = events.target.value; | |
this.set(val); | |
} | |
show() { | |
let txt = this.showEle.textContent; | |
let self = this; | |
//todo 此处过于简陋 | |
if(!this.key) { | |
this.showEle.textContent = txt.replace(this.pattern, (match, key) => { | |
self.key = key; | |
return self.data[key]; | |
}).toString(); | |
} else { | |
this.showEle.textContent = self.data[this.key]; | |
} | |
} | |
set(value = this.defuault[this.key]) { | |
this.data[this.key] = value; | |
this.inputEle.value = this.data[this.key]; | |
this.show(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment