gpt4 book ai didi

javascript - 如何让 Knockout 更新全局变量变化

转载 作者:行者123 更新时间:2023-11-30 14:34:50 25 4
gpt4 key购买 nike

我正在使用 knockout 绑定(bind)某些输入框上的值。我还设置了模型以订阅全局变量(数据)的值。

function AppViewModel() {
this.username = ko.observable(data.user.name);
this.name = ko.observable(data.visibleByRegisteredUsers.name);
this.phone = ko.observable(data.visibleByRegisteredUsers.phone);
this.gender = ko.observable(data.visibleByRegisteredUsers.gender);
this.distance = ko.observable(data.visibleByRegisteredUsers.distance);
this.address = ko.observable(data.visibleByRegisteredUsers.address);
this.postcode = ko.observable(data.visibleByRegisteredUsers.postcode);
this.latitude = ko.observable(data.visibleByRegisteredUsers.latitude);
this.longitude = ko.observable(data.visibleByRegisteredUsers.longitude);

this.name.subscribe(function (newData) {
data.visibleByRegisteredUsers.name = newData;
});
this.phone.subscribe(function (newData) {
data.visibleByRegisteredUsers.phone = newData;
});
this.gender.subscribe(function (newGender) {
data.visibleByRegisteredUsers.gender = newGender;
});
this.distance.subscribe(function (newData) {
data.visibleByRegisteredUsers.distance = newData;
});
this.address.subscribe(function (newData) {
data.visibleByRegisteredUsers.address = newData;
});
this.postcode.subscribe(function (newData) {
data.visibleByRegisteredUsers.postcode = newData;
});
this.latitude.subscribe(function (newData) {
data.visibleByRegisteredUsers.latitude = newData;
});
this.longitude.subscribe(function (newData) {
data.visibleByRegisteredUsers.longitude = newData;
});


}

ko.applyBindings(new AppViewModel());

我像这样绑定(bind)输入值:

<input type="text" class="form-control" placeholder="Lat" id="lat" aria-describedby="basic-addon1" required data-bind="value:latitude">

如果我随后更新数据对象,例如为 data.visibleByRegisteredUsers.latitude 设置值,则输入框不会更新。我的设置方式有什么不正确的地方吗?

最佳答案

您正在使用存储在 data 对象及其嵌套内容中的值初始化您的 View 模型的属性。

初始化(例如:this.latitude = ko.observable(someValue))之后,您的可观察对象只不过是一个带有值的包装器。使用新值调用包装器并进行更新。 (this.latitude(10)) 在没有值的情况下调用它并解包。 (this.latitude();//10)

即:初始化后,您不应该触摸 data 对象。您可以通过更新 View 模型来进行更改。如果要解析回原始格式,则必须自己编写逻辑。

const data = {
visibleByRegisteredUsers: {
latitude: 54
}
};

function AppViewModel() {
/* ... */
this.latitude = ko.observable(data.visibleByRegisteredUsers.latitude);

this.latitude.subscribe(console.log);
};

ko.applyBindings(new AppViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input data-bind="textInput: latitude">

关于javascript - 如何让 Knockout 更新全局变量变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50583403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com