我有一个 knockout 可观察:self.productBarcode = ko.observable(),并且我使用jquery自动完成在产品列表中搜索,如果找到产品,我有一个选择事件自动完成功能将所选对象添加到可观察对象中:
select: function (event, ui) {
updateElementValueWithLabel(event, ui);
self.productBarcode(ui);
ui 对象具有以下格式:
ui
{
item
{
barcode: "2"
label: "p1"
value: "p1"
}
}
然后我需要从productBarcode中选择与ui格式相同的产品barcode。
问题:如何从可观察的 productBarcode 访问条形码属性? 我尝试过以下方法:
self.addNewSale = function() {
var placeNewSale = {
StoreId: self.SaleStoreObject().Id,
StoreName: self.SaleStoreObject().Name,
ProductBarcode: self.productBarcode().barcode,
ProductName: self.productBarcode().label,
Quantity: self.newSale.Quantity()
}
self.placeSaleProducts().push(placeNewSale);
self.placeSaleProducts(self.placeSaleProducts());
}
最佳答案
当您像这样定义 ko.observable
时:
self.productBarcode = ko.observable();
其初始值将是未定义
。这意味着您不能通过执行以下操作来盲目访问其属性:
var currentBarcode = self.productBarcode().item.barcode;
这将导致 javascript 尝试访问 undefined
的 item
属性,但它无法访问...
您可以检查未定义
,或者使用更短但不太“安全”的错误检查:
// Option 1: Explicitly check for undefined:
var current = self.productBarcode(),
currentBarcode = (typeof current !== "undefined") ? current.item.barcode : null;
// Option 2: Check if there's "something truthy" in the observable
var current = self.productBarcode(),
currentBarcode = current ? current.item.barcode : null;
关于javascript - knockout 可观察的访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265161/