如何实现JS原生数据双向绑定
短信预约 -IT技能 免费直播动态提醒
这篇文章主要介绍如何实现JS原生数据双向绑定,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
代码如下:
<span deep="7"><!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
function DataBinder( object_id ) {
// Create a simple PubSub object
var pubSub = {
callbacks: {},
on: function( msg, callback ) {
this.callbacks[ msg ] = this.callbacks[ msg ] || [];
this.callbacks[ msg ].push( callback );
},
publish: function( msg ) {
this.callbacks[ msg ] = this.callbacks[ msg ] || [];
for ( var i = 0, len = this.callbacks[ msg ].length; i < len; i++ ) {
this.callbacks[ msg ][ i ].apply( this, arguments );
}
}
},
data_attr = "bind-" + object_id,
message = object_id + ":input",
timeIn;
changeHandler = function( evt ) {
var target = evt.target || evt.class="lazy" data-srcElement, // IE8 compatibility
prop_name = target.getAttribute( data_attr );
if ( prop_name && prop_name !== "" ) {
clearTimeout(timeIn);
timeIn = setTimeout(function(){
pubSub.publish( message, prop_name, target.value );
},50);
}
};
// Listen to change events and proxy to PubSub
if ( document.addEventListener ) {
document.addEventListener( "input", changeHandler, false );
} else {
// IE8 uses attachEvent instead of addEventListener
document.attachEvent( "oninput", changeHandler );
}
// PubSub propagates changes to all bound elements
pubSub.on( message, function( evt, prop_name, new_val ) {
var elements = document.querySelectorAll("[" + data_attr + "=" + prop_name + "]"),
tag_name;
for ( var i = 0, len = elements.length; i < len; i++ ) {
tag_name = elements[ i ].tagName.toLowerCase();
if ( tag_name === "input" || tag_name === "textarea" || tag_name === "select" ) {
elements[ i ].value = new_val;
} else {
elements[ i ].innerHTML = new_val;
}
}
});
return pubSub;
}
function DBind( uid ) {
var binder = new DataBinder( uid ),
user = {
// ...
attributes: {},
set: function( attr_name, val ) {
this.attributes[ attr_name ] = val;
// Use the `publish` method
binder.publish( uid + ":input", attr_name, val, this );
},
get: function( attr_name ) {
return this.attributes[ attr_name ];
},
_binder: binder
};
// Subscribe to the PubSub
binder.on( uid + ":input", function( evt, attr_name, new_val, initiator ) {
if ( initiator !== user ) {
user.set( attr_name, new_val );
}
});
return user;
}
</script>
</head>
<body>
<input type="text" bind-1="name" />
<span bind-1="name"></span>
<script>
var DBind = new DBind( 1 );
DBind.set( "name", "" );
</script>
</body>
</html>
</span>
效果示例:
以上是“如何实现JS原生数据双向绑定”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341