hytzgroup / blog

write & read & though
0 stars 0 forks source link

双向数据绑定 #14

Open hytzgroup opened 4 years ago

hytzgroup commented 4 years ago
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./jquery.js"></script>
</head>
<body>
    <div>
        <span id="test">test</span>
        <input type="text" placeholder="请输入数据" data-bind-value="name" />
    </div>

    <script>
        function EventTarget(){
            this.hanlders = {};
        }
        EventTarget.prototype = {
            constructor:EventTarget,
            addHandler:function(type,callback){
                if(typeof this.hanlders[type] == 'undefined'){
                    this.hanlders[type] = [];
                }
                this.hanlders[type].push(callback);
            },
            removeHandler:function(type,callback){

            },
            fire:function(event){
                if(!event.target){
                    event.target = this;
                }
                var type = event.type;
                if(this.hanlders[type] instanceof Array){
                    var hanlders = this.hanlders[type];
                    for(var i = 0, len = hanlders.length; i < len; i++){
                        hanlders[i](event)
                    }
                }
            }
        };
        $(function(){

            function User(id){
                var eventTarget = new EventTarget();
                var attrs = {};
                var user = {
                    set:function(attr,value){
                        attrs[attr] = value;
                        eventTarget.fire({type:'data-bind-'+id,payload:{attr:attr,value:value}});
                    },
                    get:function(attr){
                        return attrs[attr];
                    }
                };

                // dom部分收集
                $(document).on('change',['data-bind-'+id],function(event){
                    var $this = $(event.target),
                        attr = $this.data('bind-'+id),
                        value = $this.val();
                    user.set(attr,value);
                });
                // 数据部分收集
                eventTarget.addHandler('data-bind-'+id,function(event){
                    var payload = event.payload,
                        attr = payload.attr,
                        value = payload.value;
                    $('#test').text(user.get('name'));
                    $('[data-bind-'+id+'=\"'+attr+'\"]').val(value);
                });
                return user;
            }

            var user = new User('value');
            user.set('name','123123');
            $('#test').text(user.get('name'));

        });
    </script>

</body>
</html>