javascript - knockout 可观察的访问属性

标签 javascript jquery knockout.js

我有一个 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 尝试访问 undefineditem 属性,但它无法访问...

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

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

相关文章:

javascript - 单击后打开新选项卡后,附加到 anchor 的引导工具提示将保持打开状态

jquery - Packery + ajax 加载内容 + 重新布局 Packery

knockout.js - 使用 knockout.js 绑定(bind)到 foreach 绑定(bind)的选定项目

javascript - 单击图像会在 knockoutJS 中提供递增的值

javascript - Knockoutjs 模板 : How to use 1 object array for 2 DOM elements after filtering that array by some property?

javascript - 隐藏 div 后允许在按钮单击时重新显示

javascript - 如何使用 String.replace() 替换所有出现的模式

php - 使用ajax和表单数据发送base64图像

jquery - 为双色范围设置 jQuery UI 样式

javascript - Node.js Stream - 缓冲区到字符串给出 [object Object]