2017-03-22 78 views
1

我用下面的代碼獲得knockoutJs選定值

<select data-bind="options: preferedTimeToPickup,optionsCaption: 'Choose...', 
    optionsText: 'name',value: preferedTimeToPickupVal" id="u3413_input" class="text_sketch"> 
</select> 

在KnockoutJs

this.preferedTimeToPickup = 
     [{name:"Specific: 8:00",price:10.25}, 
     {name:"Specific:9:00",price:12.25 }, 
     {name:"Specific: 10:00",price:13.25} 
     ]; 
     this.preferedTimeToPickupVal = ko.observable(); 

當我試圖讓價格選擇使用下面的代碼選擇同時傳遞值select data

this.subtotal = ko.computed(function() { 
      return this.preferedTimeToPickupVal().price; 
}); 

我得到以下錯誤

Uncaught TypeError: Cannot read property 'preferedTimeToPickupVal' of undefined 

任何一個可以請幫我在這。

+0

我是新來的knockoutJs,我不明白這個錯誤。請解釋。 –

回答

1

由於您computed功能你指的是使用this關鍵字您的視圖模型的實例,你需要通過它的功能方面的計算

this.subtotal = ko.computed(function() { 
    // now 'this' refers to your view-model, but you first 
    // need to check if 'preferedTimeToPickupVal' is set 
    var preferred = this.preferedTimeToPickupVal(); 

    if (preferred) 
     return preferred.price; 
    else 
     return 0; 
}, this); 

此外,您還需要在您訪問price屬性之前檢查preferedTimeToPickupVal是否爲空。

請參閱Documentation

+0

@ Krishati95Dev,看到我的更新 – haim770

+0

@ojeijr,讚賞這個答案,非常感謝。 –