登录  /  注册
博主信息
博文 82
粉丝 0
评论 1
访问量 125591
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
介绍一个不知道怎么形容的小东西--Proxy
子龙的博客搬家啦httpswwwcnblogscomZiLongZiLong
原创
1104人浏览过

what's this?

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

It's means that you can define the fundamental  behavior to control the object that you currently use.Such as read a property of the object,  you can define a get trap method of the handler that is the second parmater of the proxy 's constructor ,or set a property you can use set trap method.And so on.

Just like it's name, proxy is a middle-ware  between your operation and actual object recived the opreation. 

英文写的好吃力...还是继续写中文吧

那么我们可以基于此做些什么好玩的事呢?首先你们有没有注意到:这个东西和es5里边的寄存器方法很像,所以我们可以简易的实现一个单向的数据绑定:

let modal = new Proxy(
    {
        data:{},
        bindList:{},
        /*  
         * @param {DomElement} entry dom节点
         * @param {String} prop 要绑定的属性
         * @param {String} data 该属性对应的数据名称
        bind:function(entry,prop,data){
            let self = this;
            if( !this.bindList[data] )
                this.bindList[data] = [];
            this.bindList[data].push(function(){
                entry[prop] = self['data'][data]
            })
        }
    },{
        get:function( obj, prop,reviver){
            if( prop == 'data' || prop == 'bindList' || prop == 'bind' )
                return obj[prop]
            return obj['data'][prop] ? obj['data'][prop] : undefined;
        },
        set:function( obj, data, value){
            let index = 0;
            
            obj['data'][data] = value;
            while( obj['bindList'][data][index] ){
                obj['bindList'][data][index]();
                index++;
            }

        }
    })

怎么玩呢?我们只需要调用modal的bind方法,然后将需要绑定的属性跟对应的data的名字一起传入即可。当然啦,这东西只能玩一下,如果真的要在实际项目中运用估计性能会成为一大难题,因为整个数据绑定的核心我是使用了闭包函数完成的。

之所以开篇写不知道怎么形容是因为我总觉得这玩意能搞大事情,但是另一方面,你在使用它的时候要完成某种操作很可能要使用与原来截然不同的方式去完成,所以到底是编程利器还是其他的东西 ,只能拭目以待了。还有以前使用avalone时avalone的define方法返回来的东西也是个proxy所以影响深刻,当然了此proxy非彼proxy只是名字相似罢了。

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学