为什么在knockout.js中设置observable不起作用

时间:2013-11-29 06:18:46

标签: knockout.js

我正在尝试在某些observable上显式设置默认值,但在设置它们并检查它们的值后,它们将返回undefined。我做错了什么?

有趣的是,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();
});

1 个答案:

答案 0 :(得分:2)

下拉列表为空。值被设置为某种东西。

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