knockout:没有默认值的 ko observable

vum*_*sha 3 javascript knockout.js

我刚刚学习淘汰赛,偶然发现了使用列表的教程。

function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);

    self.formattedPrice = ko.computed(function() {
        var price = self.meal().price;
        return price ? "$" + price.toFixed(2) : "None";        
    });
}
Run Code Online (Sandbox Code Playgroud)

在本教程中,此代码定义了可观察的膳食,这将是在下拉选择中选择的选项。如果我没有默认值,例如我想使用单选组而不是选择。我希望能够创建一个没有任何默认值的可观察值。我尝试使用空字符串作为默认值,然后它就可以了

self.meal = ko.observable("");
Run Code Online (Sandbox Code Playgroud)

而如果我尝试将 null 作为默认值,则选择选项甚至不会出现。

self.meal = ko.observable(null); // not working
Run Code Online (Sandbox Code Playgroud)

创建没有默认值的可观察值的正确方法是什么?

nem*_*esv 5

当然你可以将你的 observable 初始化null

 self.meal = ko.observable(null);
Run Code Online (Sandbox Code Playgroud)

或者undefined

 self.meal = ko.observable();
Run Code Online (Sandbox Code Playgroud)

然而,在这种情况下,您必须处理 ifmeal事实上的情况null,或者undefined因为当您编写类似的内容时,self.meal().price;它会抛出异常,因为您尝试访问“nothing”的属性

所以你需要修复formattedPrice计算的:

self.formattedPrice = ko.computed(function() {
    if (!self.meal())
        return "None";
    var price = self.meal().price;
    return price ? "$" + price.toFixed(2) : "None";        
});    
Run Code Online (Sandbox Code Playgroud)

totalSurcharge计算出检查情况self.meal()

self.totalSurcharge = ko.computed(function() {
   var total = 0;
   for (var i = 0; i < self.seats().length; i++)
   {
       if (self.seats()[i].meal())
       total += self.seats()[i].meal().price;
   }
   return total;
}); 
Run Code Online (Sandbox Code Playgroud)

演示JSFiddle

注意:它偶然使用空字符串(因为空字符串是一个对象,因此访问它们的属性是有效的,但self.meal().price所有这些都将返回未定义),因此它不是一个正确的解决方案。