gpt4 book ai didi

Knockout.js - 如何在两个数组之间交叉引用对象

转载 作者:行者123 更新时间:2023-12-01 12:35:58 28 4
gpt4 key购买 nike

我有两个模型:

var ProductModel = function(productid, productname, producttypeid, productprice) {
var self = this;
self.ProductId = productid;
self.ProductName = productname;
self.ProductTypeId = producttypeid;
self.ProductPrice = productprice;
}

var ProductTypeModel= function(producttypeid, producttypename) {
var self = this;
self.ProductTypeId = producttypeid;
self.ProductTypeName = producttypename;
}

我在 View 模型中使用它们:

var ProductViewModel = function() {
var self = this;
self.ProductList = ko.observableArray([]);
self.ProductTypeList = ko.observableArray([]);

//...init 2 array and some misc methods
}

在 html 文件中:

...
<table>
<thead>
<tr>
<th>Id</th>
<th>Type</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody data-bind="template: { name: 'row', foreach: ProductList }">
</tbody>
</table>
...
<script id="row" type="html/template">
<tr>
<td data-bind="html: ProductId"></td>
<td data-bind="html: ProductName"></td>
<td data-bind="html: ProductTypeId"></td> <!-- I stuck here!!! -->
<td data-bind="html: ProductPrice"></td>
</tr>
</script>
...

我希望我的表显示 ProductTypeName 而不是 ProductTypeId,但我无法将 ProductTypeId 传递到任何函数以获取 ProductTypeName。

最佳答案

var ProductViewModel = function() {
var self = this;
self.ProductList = ko.observableArray([]);
self.ProductTypeList = ko.observableArray([]);

//...init 2 array and some misc methods

self.getProductTypeName = function (productTypeId) {
var typeId = ko.unwrap(productTypeId),
found = ko.utils.arrayFirst(self.ProductTypeList(), function (productType) {
return ko.unwrap(productType.ProductTypeId) === typeId;
});

return found ? ko.unwrap(found.ProductTypeName) : null;
};
};

<script id="row" type="html/template">
<tr>
<td data-bind="html: ProductId"></td>
<td data-bind="html: ProductName"></td>
<td data-bind="html: $root.getProductTypeName(ProductTypeId)"></td>
<td data-bind="html: ProductPrice"></td>
</tr>
</script>

关于Knockout.js - 如何在两个数组之间交叉引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29757118/

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