按照我的理解,我有一个 HTML 元素,它绑定(bind)到 koObservableArray 中的特定属性。由于结构的设置,它没有绑定(bind)到自己的 koObservable。
<input data-bind="value: A" id="x" />
提交表单时,将调用一个方法,将 knockout View 模型序列化为 JSON。
这工作正常,但现在我在表单上添加一些输入清理。
function sanitize(){
//compute sanitized value
document.getElementById("x").value = sanitized_value;
}
现在,显然这也不会更新 knockout View 模型。我的问题是:给定一个特定的 html 元素(绑定(bind)到 koObservableArray 中的属性),如何强制 koObservableArray 中的属性也更新?
理想情况下,我需要能够在不更改任何 knockout 代码的情况下完成此操作。我真正想要做的是用 JavaScript 模拟任何导致 knockout View 模型更新的因素。我知道它会在模糊时更新,但调用:
document.getElementById("x").blur();
没有导致 View 模型更新。
最佳答案
不是自作聪明,但你做错了:)如果你使用 knockout ,你必须始终在 View 模型上进行操作。逻辑、清理等永远不应该直接接触 DOM。考虑一下您希望 View 模型绑定(bind)到不同模板的情况。保持逻辑分离是 knockout 的重点。
现在,这并不能解决你的问题,但如果我说服了你,这将是:要做你所说的,你需要一个可观察值的 observableArray 。因此,当您创建可观察数组时,将可观察值插入其中,然后更改它们:
var viewModel = {
mainArray: ko.observableArray()
};
// I understand you've got some probably complex mapping logic, let's say you get your array from the server, and then assign it like this:
viewModel.mainArray(arrayFromServer);
// In that case, do this:
ko.utils.arrayForEach(arrayFromServer, function(item) {
item.A = ko.observable(item.A);
});
viewModel.mainArray(arrayFromServer);
// and now if you're worried about the trip back to the server:
var jsonStringForServer = viewModel.toJSON();
var plainJSObjectForServer = viewModel.toJS();
关于javascript - 如何强制对特定 HTML 元素进行 knockout 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537805/