我正试图从observableArray中找到索引(主要是从这里获取产品价格)。
我正在使用indexOf
但它总是返回-1
我的观点模型是.
var myviewmodel = function(){
var self = this;
self.SetId = ko.observable();
self.ProductId=ko.observable();
self.Productname=ko.observable();
self.Products = ko.observableArray([{"ProductId":"5dca48ae-5378-4c2b-a8ea-17702b722d4f","Productname":"Prd1","Price":12.00},{"ProductId":"8b91a6e6-e9b4-4dc4-b32d-2fdba61cb707","Productname":"Prd2","Price":777.00}]);
self.changeProp = function (text) {
var AllProducts = text.Products();
console.log(ko.toJSON(AllProducts));
console.log(self.SetId());
//var thisindex = text.Products().indexOf(self.SetId());
var thisindex = AllProducts.indexOf(self.SetId());//text.Products().length;
console.log(thisindex);
//var Price = text.Products()[thisindex].Price;
// console.log("Price: "+ Price);
}
}
ko.applyBindings(new myviewmodel());
我使用的是knockout.js 2.1.0版
任何人请告诉我解决方案。我在这里复制了代码。
通过optionsValue: 'ProductId'
设置,您可以告诉KO使用您的ProductId
值来存储在SetId
属性中。
然而,在AllProducts
中,您仍然存储整个产品对象,因此AllProducts.indexOf(self.SetId());
当然会返回-1,因为它不知道应该将SetId
与哪个属性进行比较。
一种解决方案是从包含ID的AllProducts
创建一个具有ko.utils.arrayMap
的新阵列,并在该阵列上使用indexOf
:
var thisindex = ko.utils.arrayMap(AllProducts, function(item){
return item.ProductId; }).indexOf(self.SetId());
console.log(thisindex);
演示JSFiddle。
或者,您可以告诉KO在SetId
属性中设置您的整个Product对象(在这种情况下,您可能应该重命名该属性),同时删除optionsValue: 'ProductId'
设置,在这种情况中,您根本不需要indexOf
调用,您只需编写:
console.log("Price: "+ self.SetId().Price);
演示JSFiddle。
或者,如果你只需要价格,你可以使用optionsValue: 'Price'
,在这种情况下,SetId
属性将直接存储所选价格。