码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-07-04 22:56:06      阅读:476      评论:0      收藏:0      [点我收藏+]

标签:bin   com   use   简单   type   each   rop   val   func   

<!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>

 

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

标签:bin   com   use   简单   type   each   rop   val   func   

原文地址:https://www.cnblogs.com/catgatp/p/9265437.html

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