Skip to content

Instantly share code, notes, and snippets.

@zenHeart
Created June 9, 2018 07:47
Show Gist options
  • Save zenHeart/0bcb74759bd4c64bafef1420a420716a to your computer and use it in GitHub Desktop.
Save zenHeart/0bcb74759bd4c64bafef1420a420716a to your computer and use it in GitHub Desktop.
双向数据绑定
<!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>
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