在knockoutJs中获取选定的值

时间:2017-03-22 12:58:09

标签: javascript knockout.js

我使用以下代码

将值传递给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

任何人都可以帮助我。

1 个答案:

答案 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是否为空。

请参阅Documentation