JS原生数据双向绑定实现代码
程序员文章站
2022-11-25 10:30:44
代码如下:
&l...
代码如下:
<span style="font-family:times new roman;font-size:14px;" 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.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原生数据双向绑定实现代码,希望对大家有所帮助
下一篇: js移动端事件基础及常用事件库详解