gpt4 book ai didi

javascript - Knockout JS 数据绑定(bind)不起作用

转载 作者:行者123 更新时间:2023-11-30 00:02:48 29 4
gpt4 key购买 nike

当我在 applyBidnigns 行设置调试器时,我可以看到以下内容: enter image description here

所有属性都保留一个实际值,但我无法将它们中的任何一个映射到我的渲染中。表单完全是空的。

绑定(bind)模型:

$(document)
.ready(function() {
ko.applyBindings(wqsvm, jQuery('#div_wQualitySearch')[0]);
});

function ViewModel() {
var self = this;
self.search = ko.observable(new Search());
self.submit = function() {
if (validator != null && validator.validate('waterqualitysearch')) {
self.search.geolocation = getGeocodeByZip(self.search.geolocation.zip);
window.location.href = '#' + self.search.buildUrl() + self.buildUrl();
}
};
self.buildUrl = function() {
var locHash = encodeQueryData(self);
return locHash;
};
}
function Search() {
var self = this;
self.zip = ko.observable('');
self.distance = ko.observable(25);
self.currentPage = ko.observable(1);
self.pageSize = ko.observable(10);
self.availableRadiuses = ko.observableArray([25, 50, 100, 200, 250]);
self.geolocation = ko.observable(new geoLocation());
self.buildUrl = function () {
var locHash = encodeQueryData(self);
return locHash;
}
self.initFromUrl = function() {
var locHash = window.location.hash.substring(1);
var location = JSON.parse('{"' +
decodeURI(locHash).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
self.geolocation(new geoLocation(0, 0, '', location));
if (location.zip !== 'undefined')
self.zip(location.zip);
if (location.distance !== 'undefined')
self.distance(location.distance);
if (location.currentpage !== 'undefined')
self.currentPage(location.currentpage);
},
self.initialize = function() {
if (window.location.hash) {
self.initFromUrl();
}
}
self.initialize();
}
var wqsvm = new ViewModel();

渲染:

<div class="find-form" id="div_wQualitySearch">
<input type="text" id="txt_QWaterZip" placeholder="ZIP Code" data-bind="value: search.zip">
<select id="ddl_Radius" placeholder="Radius" data-bind="options: search.availableRadiuses, value: search.distance"></select>
<a data-bind="click: submit, attr: {'class': 'button dark-blue'}" id="btn-waterSearch">Search</a>
</div>

最佳答案

我将发布答案以在将来帮助其他人。感谢@haiim770,我能够解决这个问题。

搜索不需要成为可观察的。不过,您仍然可以尝试 value: search().zip 等(这是因为 Knockout 不会自动解包作为表达式一部分的可观察对象,它只会自动解包对可观察对象的直接引用 [如 value: SomeObservable])。底线是,尝试: self.search = new Search();相反。

function ViewModel() {
var self = this;
self.search = new Search();
self.submit = function() {
if (validator != null && validator.validate('waterqualitysearch')) {
self.search.geolocation = getGeocodeByZip(self.search.geolocation.zip);
window.location.href = '#' + self.search.buildUrl() + self.buildUrl();
}
};
self.buildUrl = function() {
var locHash = encodeQueryData(self);
return locHash;
};
}

关于javascript - Knockout JS 数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39705963/

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