码迷,mamicode.com
首页 > 其他好文 > 详细

defineProperties属性的运用==数据绑定

时间:2017-09-07 00:50:26      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:targe   for   fine   val   config   attrs   conf   div   赋值   

传送门

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

<script>

/*
    defineProperties
    可以定义属性访问器
    如果使用了value,就不能使用set,get的方法
    enumerable:true 是可以使用for in 枚举出来的
    configurable:true 是否可以修改value值
    在传入的对象里写对象会被赋值undefined 如:defineObj["___private"]={},___private键值为undefined
    使用defineProperties方法可以监听数据的更改

*/

function bindData(obj,opt){
    var defineObj={};
    for(var attrs in obj){
        defineObj["___"+attrs]={
            value:obj[attrs],
            writable: true,
            enumerable: true,
            configurable: true
        };
        (function(attrs){
            defineObj[attrs]={
            set: function (x) {
                this["___"+attrs]=x;
                opt.getFn&&opt.getFn(x,attrs);
            },
            get: function () {
                opt.setFn&&opt.setFn(this["___"+attrs],attrs);
                return this["___"+attrs];
            },
            enumerable: false,
            configurable: true
        }
        })(attrs);
    }
    Object.defineProperties(obj,defineObj);
}

//测试数据
var model={a:"w",b:2};
bindData(model,{setFn:setFn,getFn:getFn});
function setFn(val,attr){
    console.log("setFn:"+attr+":"+val);
}
function getFn(val,attr){
    console.log("getFn:"+attr+":"+val);
}
</script>

 

defineProperties属性的运用==数据绑定

标签:targe   for   fine   val   config   attrs   conf   div   赋值   

原文地址:http://www.cnblogs.com/zhangzhicheng/p/7487663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!