【问题标题】:Access properties of knockout observable敲除 observable 的访问属性
【发布时间】:2016-09-01 15:49:51
【问题描述】:

我有一个可观察的淘汰赛: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());
} 

【问题讨论】:

  • 我不完全清楚你在问什么......预期的行为是什么,你当前代码的结果是什么? (另外,请注意,您可以通过在 .push 之前省略 () 直接推送到 observableArray
  • 我正在尝试从具有 ui 格式的对象访问条形码属性
  • 喜欢obj.item.barcode?
  • 我无法直接访问类似:self.productBarcode().barcode,因为我知道这是 undefined
  • 是的,像 obj.item.barcode 之类的东西

标签: javascript jquery knockout.js


【解决方案1】:

当您像这样定义ko.observable 时:

self.productBarcode = ko.observable();

它的初始值为undefined。这意味着您不能通过执行以下操作来盲目地访问其属性:

var currentBarcode = self.productBarcode().item.barcode;

这将导致 javascript 尝试访问 undefineditem 属性,但它无法...

您可以检查undefined,或者使用更短但不太“安全”的错误检查:

// 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2014-07-07
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    相关资源
    最近更新 更多