Vue.js双向数据绑定实现

js中对象属性类型有数据属性和访问器属性,这里实现简单的双向数据绑定是利用了对象的访问器属性中包含的get和set

修改属性的默认特性使用Object.defineProperty()方法

addEventListener(event,function,useCapture)绑定事件,实时检测,useCapture可选布尔值,默认为false,事件在冒泡阶段执行。

事件触发过程中,DOM事件流包含三个阶段:事件捕获,处于目标,事件冒泡

<input type="text" id="txt">
<span id="span"></span>

var obj = {};
//obj定义一个名字为hello的访问器属性
Object.defineProperty(obj,"hello",{
    get:function(){
        console.log("get方法被调用了");
    },
    set:function(val){
        console.log('set方法被调用了,参数是' + val);
    }
});

obj.hello; //get方法被调用了
obj.hello = "nihao"; //set方法被调用了,参数是nihao


var obj = {};
Object.defineProperty(obj,'hello',{
    set:function(newVal){
        document.getElementById('txt').value = newVal;
        document.getElementById('span').innerHTML = newVal;
    }
});
document.addEventListener('keyup',function(e){
    console.log(e.target);
    obj.hello = e.target.value;
},true);


猜你喜欢

转载自blog.csdn.net/xiaoqingpang/article/details/78919138