下面是我给大家整理的js原生代码实现数据双向绑定,有兴趣的同学可以去看看。
封装成jquery的插件了,复制代码后在Jquery之后引入;
也可以去掉插件那行直接使用。
<!--使用方法-->
<div data-bind-1="name"></div>
<input type="text" data-bind-1="name" />
<script>
$.DBind(1).set("name", "123");
</script>(function() {
//封装成jqery插件
jQuery.DBind = function(id) {
return new DBind(id);
}; //下面是具体的实现
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 = "data-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;
}
})();上面是我整理给大家的js原生代码实现数据双向绑定,希望今后会对大家有帮助。
相关文章:
通过代码详细为你讲解如何在js中创建div,span,label
以上就是js原生代码实现数据双向绑定(可以直接拿来使用,已经封装好了)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号