function Vue(options){
this.data = options.data;
var id = options.el;
var dom = nodeContainer(document.getElementById(id),this);
document.getElementById(id).appendChild(dom);
}
//随后使用他
var Demo = new Vue({
el:'mvvm',
data:{
text:'HelloWorld',
d:'123'
}
})
接下去的具体得初始化内容
//编译
function compile(node, vm){
var reg = /\{\{(.*)\}\}/g;//匹配双绑的双大括号
if(node.nodeType === 1){
var attr = node.attributes;
//解析节点的属性
for(var i = 0;i < attr.length; i++){
if(attr.nodeName == 'v-model'){
var name = attr.nodeValue;
node.value = vm.data[name];//讲实例中的data数据赋值给节点
//node.removeAttribute('v-model');
}
}
}
//如果节点类型为text
if(node.nodeType === 3){
if(reg.test(node.nodeValue)){
// console.dir(node);
var name = RegExp.$1;//获取匹配到的字符串
name = name.trim();
node.nodeValue = vm.data[name];
}
}
}
function observe (obj,vm){
Object.keys(obj).forEach(function(key){
defineReactive(vm,key,obj[key]);
})
}
然后再Vue方法中初始化:
function Vue(options){
this.data = options.data;
var data = this.data;
-------------------------
observe(data,this);//这里调用定义响应式方法
-------------------------
var id = options.el;
var dom = nodeContainer(document.getElementById(id),this);
document.getElementById(id).appendChild(dom); //把虚拟dom渲染上去
}
在编译方法中v-model属性找到的时候去监听:
function compile(node, vm){
var reg = /\{\{(.*)\}\}/g;
if(node.nodeType === 1){
var attr = node.attributes;
//解析节点的属性
for(var i = 0;i < attr.length; i++){
if(attr.nodeName == 'v-model'){
var name = attr.nodeValue;
-------------------------//这里新添加的监听
node.addEventListener('input',function(e){
console.log(vm[name]);
vm[name] = e.target.value;//改变实例里面的值
});
-------------------------
node.value = vm[name];//讲实例中的data数据赋值给节点
//node.removeAttribute('v-model');
}
}
}
}
var sub1 = {
update:function(){
console.log(1);
}
}
var sub2 = {
update:function(){
console.log(2);
}
}
var sub3 = {
update:function(){
console.log(3);
}
}
每个订阅者对象内部声明一个update方法来触发订阅属性。
再声明一个发布者,去触发发布消息,通知的方法::
function Dep(){
this.subs = [sub1,sub2,sub3];//把三个订阅者加进去
}
Dep.prototype.notify = function(){//在原型上声明“发布消息”方法
this.subs.forEach(function(sub){
sub.update();
})
}
var dep = new Dep();
//pub.publish();
dep.notify();
我们也可以声明另外一个中间对象
var dep = new Dep();
var pub = {
publish:function(){
dep.notify();
}
}
pub.publish();//这里的结果是跟上面一样的