【发布时间】:2014-10-14 20:07:39
【问题描述】:
我正在阅读this article,但由于某种原因,我无法让这段代码在 chrome 中运行 - IE9 可以正常运行。
这里是js:
$(document).ready(function() {
function DataBinder( object_id ) {
// Use a jQuery object as simple PubSub
var pubSub = jQuery({});
// We expect a `data` element specifying the binding
// in the form: data-bind-<object_id>="<property_name>"
var
data_attr = "bind-" + object_id,
message = object_id + ":change";
// Listen to change events on elements with the data-binding attribute and proxy
// them to the PubSub, so that the change is "broadcasted" to all connected objects
jQuery( document ).on( "change", "[data-" + data_attr + "]", function( evt ) {
var $input = jQuery( this );
console.dir('test message');
pubSub.trigger( message, [ $input.data( data_attr ), $input.val() ] );
});
// PubSub propagates changes to all bound elements, setting value of
// input tags or HTML content of other tags
pubSub.on( message, function( evt, prop_name, new_val ) {
jQuery( "[data-" + data_attr + "=" + prop_name + "]" ).each( function() {
var $bound = jQuery( this );
if ( $bound.is("input, textarea, select") ) {
$bound.val( new_val );
} else {
$bound.html( new_val );
}
});
});
return pubSub;
};
function User( uid ) {
var binder = new DataBinder( uid ),
user = {
attributes: {},
// The attribute setter publish changes using the DataBinder PubSub
set: function( attr_name, val ) {
this.attributes[ attr_name ] = val;
binder.trigger( uid + ":change", [ attr_name, val, this ] );
},
get: function( attr_name ) {
return this.attributes[ attr_name ];
},
_binder: binder
};
// Subscribe to the PubSub
binder.on( uid + ":change", function( evt, attr_name, new_val, initiator ) {
if ( initiator !== user ) {
user.set( attr_name, new_val );
}
});
return user;
};
var user = new User( 123 );
user.set( "name", "Wolfgang" );
});
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>test</title>
<script src="../../jquery/jquery.js"></script>
</head>
<body>
<input type="number" data-bind-123="name" />
<script src="js/myjsfile.js"></script>
</body>
</html>
我添加了 console.dir('test message') ,当输入框上触发更改事件时应该记录它。在 IE 中我看到这条消息,但在 Chrome 中我没有。
【问题讨论】:
标签: javascript jquery data-binding