2016-09-01 49 views
0

我有一个基因敲除可观察到:self.productBarcode = ko.observable(),我用jquery自动完成在产品列表中搜索,如果发现产品我有一个select事件自动完成功能添加到选定的可观察对象:访问属性的基因敲除

select: function (event, ui) { 
       updateElementValueWithLabel(event, ui); 
       self.productBarcode(ui); 

UI对象的格式如下:

ui 
{ 
    item 
    { 
     barcode: "2" 
     label: "p1" 
     value: "p1" 
    } 
} 

那我需要的是SEL等产品条形码productBarcode它们具有与ui相同的格式。

问题:如何从可观察的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()); 
} 
+0

它我不清楚你在问什么......期望的行为是什么,你现在的代码有什么结果? (另外,请注意,您可以通过在'.push'前面省略'()来直接推入'observableArray') – user3297291

+0

我试图从具有** ui *格式的对象访问条形码属性* – sixfeet

+1

像'obj.item.barcode'? – user3297291

回答

1

当你定义一个ko.observable像这样:

self.productBarcode = ko.observable(); 

其初始值将是undefined。这意味着,通过做这样的事情,你不能盲目地访问它的属性:

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

这将导致在JavaScript试图访问的undefineditem性质,它不能...

你可以检查undefined,或用较短,但不那么 “安全” falsey检查去:

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