我正在处理由几个下拉框组成的数据输入表单。
我从Web Api调用的下拉框中加载数据。返回的数据有3个值,Id,Value和Code。我将数据加载到observableArray,我可以将数据绑定到下拉框。
我遇到问题的地方是将下拉列表中的值值加载到计算值。我最初得到一个NaN,当我做出选择时,我得到了[object Object][object Object]
。
这是我正在做的一个例子:
脚本
var CountryData =
[{"$id":"1","Code":"AMERICA","Value":"A"},
{"$id":"2","Code":"FRANCE","Value":"F"},
{"$id":"3","Code":"GERMANY","Value":"G"}]
var ProductData =
[{"$id":"1","Code":"Product1","Value":"1001"},
{"$id":"2","Code":"Product2","Value":"1002"},
{"$id":"3","Code":"Product3","Value":"1003"}]
var CountryViewModel = function () {
var self = this;
self.country = ko.observableArray(CountryData);
self.countryselected = ko.observable().publishOn("countryselected");
};
var ProductViewModel = function() {
var self = this;
self.product = ko.observableArray(ProductData);
self.productselected = ko.observable().publishOn("productselected");
};
var ProductCodeModel = function () {
this.country = ko.observable().subscribeTo("countryselected");
this.product = ko.observable().subscribeTo("productselected");
this.productCode = ko.computed(function() {
return this.country() + this.product();
}, this);
};
var masterVM = {
countryModel: new CountryViewModel(),
productModel: new ProductViewModel(),
productCodeModel: new ProductCodeModel()
};
ko.applyBindings(masterVM);
和HTML
<table>
<tr>
<td><b>Country: </b></td>
<td><select data-bind="options: countryModel.country, optionsText: 'Code', value: countryModel.countryselected, optionsCaption: 'Choose...'"></select></td>
</tr>
<tr>
<td><b>Product: </b></td>
<td><select data-bind="options: productModel.product, optionsText: 'Code', value: productModel.productselected, optionsCaption: 'Choose...'"></select></td>
</tr>
</table>
<br />
<br />
<div>ProductCode</div>
<div data-bind="with: productCodeModel">
<span data-bind="text: productCode"></span>
</div>
这是一个小提琴http://jsfiddle.net/drfiasco/A6xpX/
我已经查看了映射插件,但我似乎无法让它工作。
答案 0 :(得分:1)
您需要访问两个observable的Code字段。目前,您只是将两个对象分开。
this.productCode = ko.computed(function() {
if(this.country() && this.product())
return this.country().Code + this.product().Code;
else
return "Please Make Selection Above";
}, this);