[转]js实现简单的双向数据绑定
轉(zhuǎn)自:http://www.see-source.com/blog/300000038/444
雙向數(shù)據(jù)綁定指的就是,綁定對(duì)象屬性的改變到用戶界面的變化的能力,反之亦然。換種說法,如果我們有一個(gè)user對(duì)象和一個(gè)name屬性,一旦我們賦了一個(gè)新值給user.name,在UI上就會(huì)顯示新的姓名了。同樣地,如果UI包含了一個(gè)輸入用戶姓名的輸入框,輸入一個(gè)新值就應(yīng)該會(huì)使user對(duì)象的name屬性做出相應(yīng)的改變。
很多熱門的JS框架客戶端如Ember.js,Angular.js?或者KnockoutJS?,都在最新特性上刊登了雙向數(shù)據(jù)綁定。這并不意味著從零實(shí)現(xiàn)它很難,也不是說需要這些功能的時(shí)候,采用這些框架是唯一的選擇。下面的想法實(shí)際上很基礎(chǔ),可以被認(rèn)為是3步走計(jì)劃:
還是有很多方法能夠?qū)崿F(xiàn)上面的想法,有一個(gè)簡(jiǎn)單有效的方法就是使用PubSub模式。?這個(gè)思路很簡(jiǎn)單:我們使用數(shù)據(jù)特性來(lái)為HTML代碼進(jìn)行綁定,所有被綁定在一起的JavaScript對(duì)象和DOM元素都會(huì)訂閱一個(gè)PubSub對(duì)象。只要JavaScript對(duì)象或者一個(gè)HTML輸入元素監(jiān)聽到數(shù)據(jù)的變化時(shí),就會(huì)觸發(fā)綁定到PubSub對(duì)象上的事件,從而其他綁定的對(duì)象和元素都會(huì)做出相應(yīng)的變化。
用jQuery做一個(gè)簡(jiǎn)單的實(shí)現(xiàn)
對(duì)于DOM事件的訂閱和發(fā)布,用jQuery實(shí)現(xiàn)起來(lái)是非常簡(jiǎn)單的,接下來(lái)我們就是用Jquery比如下面:
1 function DataBinder( object_id ) { 2 // Use a jQuery object as simple PubSub 3 var pubSub = jQuery({}); 4 5 // We expect a `data` element specifying the binding 6 // in the form: data-bind-<object_id>="<property_name>" 7 var data_attr = "bind-" + object_id, 8 message = object_id + ":change"; 9 10 // Listen to change events on elements with the data-binding attribute and proxy 11 // them to the PubSub, so that the change is "broadcasted" to all connected objects 12 jQuery( document ).on( "change", "[data-" + data_attr + "]", function( evt ) { 13 var $input = jQuery( this ); 14 15 pubSub.trigger( message, [ $input.data( data_attr ), $input.val() ] ); 16 }); 17 18 // PubSub propagates changes to all bound elements, setting value of 19 // input tags or HTML content of other tags 20 pubSub.on( message, function( evt, prop_name, new_val ) { 21 jQuery( "[data-" + data_attr + "=" + prop_name + "]" ).each( function() { 22 var $bound = jQuery( this ); 23 24 if ( $bound.is("input, textarea, select") ) { 25 $bound.val( new_val ); 26 } else { 27 $bound.html( new_val ); 28 } 29 }); 30 }); 31 32 return pubSub; 33 }對(duì)于上面這個(gè)實(shí)現(xiàn)來(lái)說,下面是一個(gè)User模型的最簡(jiǎn)單的實(shí)現(xiàn)方法:
1 function User( uid ) { 2 var binder = new DataBinder( uid ), 3 4 user = { 5 attributes: {}, 6 7 // The attribute setter publish changes using the DataBinder PubSub 8 set: function( attr_name, val ) { 9 this.attributes[ attr_name ] = val; 10 binder.trigger( uid + ":change", [ attr_name, val, this ] ); 11 }, 12 13 get: function( attr_name ) { 14 return this.attributes[ attr_name ]; 15 }, 16 17 _binder: binder 18 }; 19 20 // Subscribe to the PubSub 21 binder.on( uid + ":change", function( evt, attr_name, new_val, initiator ) { 22 if ( initiator !== user ) { 23 user.set( attr_name, new_val ); 24 } 25 }); 26 27 return user; 28 }現(xiàn)在我們?nèi)绻胍獙ser模型屬性綁定到UI上,我們只需要將適合的數(shù)據(jù)特性綁定到對(duì)應(yīng)的HTML元素上。
JS代碼:
1 var user = new User( 123 ); 2 user.set( "name", "Wolfgang" );HTML代碼:
1 <input type="number" data-bind-123="name" />不需要jQuery的實(shí)現(xiàn)
在如今的大多數(shù)項(xiàng)目里,可能已經(jīng)使用了jQuery,因此上面的例子完全可以接受。不過,如果我們需要試著向另一個(gè)極端做,并且還刪除對(duì)jQuery的依賴,那么怎么做呢?好,證實(shí)一下這么做并不難(尤其是在我們限制只支持IE 8及以上版本的情況下)。最終,我們必須使用一般的javascript實(shí)現(xiàn)一個(gè)定制的PubSub并且保留了DOM事件:
1 function DataBinder( object_id ) { 2 // Create a simple PubSub object 3 var pubSub = { 4 callbacks: {}, 5 6 on: function( msg, callback ) { 7 this.callbacks[ msg ] = this.callbacks[ msg ] || []; 8 this.callbacks[ msg ].push( callback ); 9 }, 10 11 publish: function( msg ) { 12 this.callbacks[ msg ] = this.callbacks[ msg ] || [] 13 for ( var i = 0, len = this.callbacks[ msg ].length; i < len; i++ ) { 14 this.callbacks[ msg ][ i ].apply( this, arguments ); 15 } 16 } 17 }, 18 19 data_attr = "data-bind-" + object_id, 20 message = object_id + ":change", 21 22 changeHandler = function( evt ) { 23 var target = evt.target || evt.srcElement, // IE8 compatibility 24 prop_name = target.getAttribute( data_attr ); 25 26 if ( prop_name && prop_name !== "" ) { 27 pubSub.publish( message, prop_name, target.value ); 28 } 29 }; 30 31 // Listen to change events and proxy to PubSub 32 if ( document.addEventListener ) { 33 document.addEventListener( "change", changeHandler, false ); 34 } else { 35 // IE8 uses attachEvent instead of addEventListener 36 document.attachEvent( "onchange", changeHandler ); 37 } 38 39 // PubSub propagates changes to all bound elements 40 pubSub.on( message, function( evt, prop_name, new_val ) { 41 var elements = document.querySelectorAll("[" + data_attr + "=" + prop_name + "]"), 42 tag_name; 43 44 for ( var i = 0, len = elements.length; i < len; i++ ) { 45 tag_name = elements[ i ].tagName.toLowerCase(); 46 47 if ( tag_name === "input" || tag_name === "textarea" || tag_name === "select" ) { 48 elements[ i ].value = new_val; 49 } else { 50 elements[ i ].innerHTML = new_val; 51 } 52 } 53 }); 54 55 return pubSub; 56 }除了設(shè)置器里調(diào)用 jQuery的trigger方法外,模型可以保持一樣。調(diào)用trigger方法將替代為調(diào)用我們定制的具有不同特征的PubSub的publish方法:
1 // In the model's setter: 2 function User( uid ) { 3 // ... 4 5 user = { 6 // ... 7 set: function( attr_name, val ) { 8 this.attributes[ attr_name ] = val; 9 // Use the `publish` method 10 binder.publish( uid + ":change", attr_name, val, this ); 11 } 12 } 13 14 // ... 15 }再次說明一下,我們用一般的純javascript的少于100行的維護(hù)代碼獲得了同樣的結(jié)果。
轉(zhuǎn)載于:https://www.cnblogs.com/zhixianyuanyangbuxianxian/p/4128018.html
總結(jié)
以上是生活随笔為你收集整理的[转]js实现简单的双向数据绑定的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全国计算机等级考试题库二级C操作题100
- 下一篇: dex2jar java 1.8_利用