我使用以下代码
将值传递给select data
<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();
当我尝试使用以下代码选择时选择价格。
this.subtotal = ko.computed(function() {
return this.preferedTimeToPickupVal().price;
});
低于错误
Uncaught TypeError: Cannot read property 'preferedTimeToPickupVal' of undefined
任何人都可以帮助我。
答案 0 :(得分: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);
此外,在您访问其preferedTimeToPickupVal
媒体资源之前,您需要检查price
是否为空。