从网上学习然后自己实现的vue双向绑定,只要input输入过多,浏览器就会崩溃,为什么?
一下是我实现的部分代码:
Observe
function Observe(data) {
this.observe(data);
}
Observe.prototype = {
observe:function(data) {
if(!data || typeof data !== 'object') return;
for(var key in data) {
this.defineReacted(data, key, data[key])
}
},
defineReacted(obj, key, val) {
this.observe(val);
var dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function() {
if(Dep.target) {
dep.addSub(Dep.target);
}
return val;
},
set:function(value) {
if(value === val) return;
val = value;
dep.notify();
}
})
}
}
Compiler
function Compiler(el, vm){
this.el = el;
this.vm = vm;
this.init();
}
Compiler.prototype = {
init: function(){
var fragment = this.createFragment(this.el);
this.compiler(fragment);
this.el.appendChild(fragment);
},
createFragment: function(el) {
var segment = document.createDocumentFragment();
var child = el.firstChild;
while(child) {
segment.appendChild(child);
child = el.firstChild;
}
return segment;
},
compiler: function(el){
var nodes = el.childNodes;
var _this = this;
if(!nodes || !nodes.length) return new Error('没有节点');
[].forEach.call(nodes, function(node){
_this.compilerElement(node);
_this.compilerAttrs(node);
if(node.childNodes) {
_this.compiler(node);
}
})
},
compilerText: function(node, exp) {
var _this = this;
var initdata = this.vm[exp];
this.updateText(node, initdata)
new Watcher(this.vm,exp,function(val) {
_this.updateText(node,val)
})
},
compilerElement: function(node) {
var reg = /\{\{(.*)\}\}/;
var content = node.textContent;
if(content && reg.test(content)) {
var text = reg.exec(content)[1];
this.compilerText(node,text);
}
},
updateText: function(node, val) {
node.textContent = val ? val : '';
}
...
}
Watcher
function Watcher(vm, ext, cb) {
this.vm = vm;
this.ext = ext;
this.cb = cb;
this.value = this.get();
}
Watcher.prototype = {
get: function() {
Dep.target = this;
var value = this.vm[this.ext];
Dep.targte = null;
return value;
},
update: function() {
var newVal = this.vm[this.ext];
var oldVal = this.value;
if(newVal === this.value) return;
this.value = newVal;
this.cb.call(this.vm,newVal,oldVal);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你把 v-model换成v-model.lazy 试试
这一块循环有问题吧