juery实现数据双向绑定
编辑时间:2019-11-08 作者:金满斗 浏览量:1573 来源:转载

js我菜

文章转自:https://blog.csdn.net/big_guo/article/details/40113309

闲话不说,上代码


<!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","dengjis");
	
	</script>
</body>
</html>


来说两句吧