Created
March 19, 2022 16:44
-
-
Save yxy/76f80bd6ad33600b9bea5a0821401bfb to your computer and use it in GitHub Desktop.
data-binder.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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"; | |
})(); |
Author
yxy
commented
Mar 19, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment