前端

www6766comJS原生数据双向绑定实现代码_javascript技巧_脚本之家

22 3月 , 2020  

以上所述是笔者给我们介绍的JS原生数据双向绑定完毕代码,希望对大家持有利于,假诺大家有任何疑问请给自个儿留言,我会及时苏醒我们的。在这里也非常感激大家对剧本之家网址的支撑!

总结

   Demo  function DataBinder { // Create a simple PubSub object var pubSub = { callbacks: {}, on: function { this.callbacks[ msg ] = this.callbacks[ msg ] || []; this.callbacks[ msg ].push; }, publish: function { this.callbacks[ msg ] = this.callbacks[ msg ] || []; for ( var i = 0, len = this.callbacks[ msg ].length; i < len; i++ ) { this.callbacks[ msg ][ i ].apply; } } }, data_attr = "bind-" + object_id, message = object_id + ":input", timeIn; changeHandler = function { var target = evt.target || evt.srcElement, // IE8 compatibility prop_name = target.getAttribute; if ( prop_name && prop_name !== "" ) { clearTimeout; timeIn = setTimeout{ 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 { var binder = new DataBinder, user = { // ... attributes: {}, set: function { this.attributes[ attr_name ] = val; // Use the `publish` method binder.publish( uid + ":input", attr_name, val, this ); }, get: function { return this.attributes[ attr_name ]; }, _binder: binder }; // Subscribe to the PubSub binder.on( uid + ":input", function( evt, attr_name, new_val, initiator ) { if  { user.set; } }); return user; }       var DBind = new DBind; DBind.set;    


相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图