用jquery实现的简单数据双向绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
    <input type="text" data-bind-0=name />
    <span data-bind-0="name" ></span>
    <script type="text/javascript">
 
    function DataBinder(object_id){
        var pubSub = jQuery({});
        var data_attr = "bind-"+object_id,
            message = object_id+":change";
        jQuery(document).on("change","[data-" + data_attr +"]",function(evt){
            var $input = jQuery(this);
            pubSub.trigger(message, [$input.attr("data-" + data_attr), $input.val()]);
        });
        pubSub.on(message, function(evt,prop_name,new_val){
            jQuery("[data-" + data_attr + "=" + prop_name + "]").each(function(){
                var $bound = jQuery(this);
                if($bound.is("input,textarea,select")) {
                    $bound.val(new_val);
                }
                else{
                    $bound.html(new_val);
                }
            });
        });
        return pubSub;
    }
 
    function User(uid){
        var binder = new DataBinder(uid),
            user = {
                attributes: {},
                set: function(attr_name,val){
                    this.attributes[attr_name] = val;
                    binder.trigger(uid + ":change", [attr_name, val, this]);
                },
 
                get: function(attr_name){
                    return this.attributes[attr_name];
                },
                _binder: binder
            };
       
          return user;
    }
 
    var user = new User(0);
    user.set("name","text");
    
    </script>
</body>
</html>

 

posted @ 2018-07-04 21:29  catgatp  阅读(8815)  评论(0编辑  收藏  举报