用jQuery做一个简单的实现
对于DOM事件的订阅和发布,用jQuery实现起来是非常简单的,接下来我们就是用Jquery比如下面:
01 |
function DataBinder( object_id ) { |
03 |
var pubSub = jQuery({}); |
07 |
var data_attr = "bind-" + object_id, |
08 |
message = object_id + ":change" ; |
12 |
jQuery( document ).on( "change" , "[data-" + data_attr + "]" , function ( evt ) { |
13 |
var $input = jQuery( this ); |
15 |
pubSub.trigger( message, [ $input.data( data_attr ), $input.val() ] ); |
20 |
pubSub.on( message, function ( evt, prop_name, new_val ) { |
21 |
jQuery( "[data-" + data_attr + "=" + prop_name + "]" ).each( function () { |
22 |
var $bound = jQuery( this ); |
24 |
if ( $bound.is( "input, textarea, select" ) ) { |
25 |
$bound.val( new_val ); |
27 |
$bound.html( new_val ); |
对于上面这个实现来说,下面是一个User模型的最简单的实现方法:
01 |
function User( uid ) { |
02 |
var binder = new DataBinder( uid ), |
08 |
set: function ( attr_name, val ) { |
09 |
this .attributes[ attr_name ] = val; |
10 |
binder.trigger( uid + ":change" , [ attr_name, val, this ] ); |
13 |
get: function ( attr_name ) { |
14 |
return this .attributes[ attr_name ]; |
21 |
binder.on( uid + ":change" , function ( evt, attr_name, new_val, initiator ) { |
22 |
if ( initiator !== user ) { |
23 |
user.set( attr_name, new_val ); |
现在我们如果想要将User模型属性绑定到UI上,我们只需要将适合的数据特性绑定到对应的HTML元素上。
2 |
var user = new User( 123 ); |
3 |
user.set( "name" , "Wolfgang" ); |
6 |
<input type= "number" data-bind-123= "name" /> |
这样输入值会自动映射到user对象的name属性,反之亦然。到此这个简单实现就完成啦!
|
|