Skip to content

Instantly share code, notes, and snippets.

@yxy
Created March 19, 2022 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yxy/76f80bd6ad33600b9bea5a0821401bfb to your computer and use it in GitHub Desktop.
Save yxy/76f80bd6ad33600b9bea5a0821401bfb to your computer and use it in GitHub Desktop.
data-binder.js
(function () {
"use strict";
var view, viewModel, valueTemplate;
valueTemplate = {
configurable: false,
enumerable: true,
get: function () {
return this._value;
},
set: function (val) {
// 更新值的时候,执行监听器动作
var i;
if (val !== this._value) {
this._value = val;
for (i = 0; i < this._listeners.length; i++) {
this._listeners[i]();
}
if (this.onChange) {
this.onChange();
}
}
},
};
function ViewModel() {
this._listeners = [];
this._value = "";
}
Object.defineProperty(ViewModel.prototype, "text", valueTemplate);
ViewModel.prototype.attach = function (fn) {
this._listeners.push(fn);
};
// this is a data-binder for input boxes
function InputBinder(elem) {
var that = this;
this._listeners = [];
this._elem = elem;
elem.onkeyup = function () {
that.value = elem.value;
};
}
InputBinder.prototype.attach = function (fn) {
this._listeners.push(fn);
};
InputBinder.prototype.onChange = function () {
this._elem.value = this.value;
};
Object.defineProperty(InputBinder.prototype, "value", valueTemplate);
// this is a data-binder for divs
function DivBinder(elem) {
this._listeners = [];
this._elem = elem;
}
DivBinder.prototype.attach = function (fn) {
this._listeners.push(fn);
};
DivBinder.prototype.onChange = function () {
this._elem.innerText = this.value;
};
Object.defineProperty(DivBinder.prototype, "value", valueTemplate);
// the view simply attaches the data-bindings
function View(viewModel, ui) {
var inputBinder = new InputBinder(ui.getElementsByTagName("input")[0]),
divBinder = new DivBinder(ui.getElementsByTagName("div")[0]);
viewModel.attach(function () {
divBinder.value = viewModel.text;
});
inputBinder.attach(function () {
viewModel.text = inputBinder.value;
});
}
viewModel = new ViewModel();
view = new View(viewModel, document.getElementById("app"));
viewModel.text = "Ready";
})();
@yxy
Copy link
Author

yxy commented Mar 19, 2022

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>

    <div id="app">
        <input type="text">
        <div></div>
    </div>
    <script src="data-binder.js"></script>

</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment