2013-11-29 49 views
0

我想明确地设置一些observables的默认值,但设置它们后,并检查它们的值,他们返回undefined。我究竟做错了什么?为什么设置在knockout.js可观察不工作

有趣的是,selectedCustomerType按预期设置,但其他2个变量selectedPlatform和selectedPricing为null。我愚蠢的错误是什么?

HTML:

<!doctype html> 
<html> 
<head> 
    <meta charset='utf-8'> 
    <script src='static/javascript/jquery-1.9.1.js'></script> 
    <script src='static/javascript/knockout-3.0.0.js'></script> 
    <script src='static/javascript/merchant.js'></script> 
</head> 

<body> 
    <div> 
    <span id='customer_types' data-bind='foreach: availableCustomerTypes()'> 
     <input data-bind='value: value, checked: $root.selectedCustomerType'> 
     <span data-bind='text: label'></span> 
    </span> 
    </div> 
    <div> 
    <select id='merchant_platforms' 
      data-bind='options: availablePlatforms(), 
         optionsText: "label", 
         optionsValue: "value", 
         value: selectedPlatform'> 
    </select> 
    </div> 
    <div> 
    <select id='merchant_pricings' 
      data-bind='options: availablePricings(), 
         optionsText: "label", 
         optionsValue: "value", 
         value: selectedPricing'> 
    </select> 
    </div> 
</body> 
</html> 

JS:

var MerchantModel = function() { 
    var self = this; 

    self.merchant = ko.observable(); 

    self.availableCustomerTypes = ko.observableArray([]); 
    // {'label': 'Red', 'value': 'R'}, 
    // {'label': 'Blue', 'value': 'B'} 
    //]); 
    self.availablePlatforms = ko.observableArray([]); 
    self.availablePricings = ko.observableArray([]); 

    // was originally setting default values here, but this gets blown away after 
    // ko.applyBindings() gets called in the $(document).ready() function below 
    self.selectedCustomerType = ko.observable(); 
    self.selectedPlatform = ko.observable(); 
    self.selectedPricing = ko.observable(); 

    // load data 
    self.load = function() { 
    self.setDefaults(); 

    // load UI lookup lists asynchronously, etc... 
    }; 

    self.setDefaults = function() { 
    self.selectedCustomerType('R'); 
    self.selectedPlatform('Tango'); 
    self.selectedPricing('Credit Plus'); 

    // calling self.selectedCustomerType() returns 'A' as expected 
    // calling self.selectedPlatform() returns undefined?? Why? 
    // calling self.selectedPricing() returns undefined?? Why?  
    }; 
} 

// activate knockout.js 
$(document).ready(function() { 
    var merchantModel = new MerchantModel(); 
    ko.applyBindings(merchantModel); 

    // load initial data via ajax (in this case just UI lookup lists, etc...) 
    merchantModel.load(); 
}); 
+0

问题是因为选项绑定选择*拒绝提供的值,因此用undefined更新了observable:即'availablePlatforms'可观察值中没有“Tango”条目。 – user2864740

+0

谢谢。这真的是'第一'正确的答案,但它是一个评论,所以我可以投票。 – lostdorje

回答

1

下拉框为空。价值被设定为某种东西。

这是无效的,值会自动调整,因为它不在下拉列表中。下拉列表中的第一项正被分配给提供的值变量。第一个项目未定义,因此您的值变得未定义。

+0

啊谢谢!我没有意识到淘汰赛实际上也在进行“验证”。我想我需要我的异步查找列表加载之前尝试设置替代默认值(即:不是列表中的第一个项目)。 – lostdorje