使用ko.computed进行绑定下拉选项的问题

时间:2015-05-21 12:28:52

标签: javascript knockout.js

我有一个模板,其中有一个下拉列表(使用自定义库),如下所示:

<select id="selectmyField" data-bind="libraryComponent: 
  { component: 'libSelect', 
    options: myViewModel.myFieldOpts, 
    value: myViewModel.myFieldSelected }">
</select>

我正在尝试使用ko.computed绑定下拉选项,并基于我从API调用获得的响应。以下是代码:

self.myFieldOpts = ko.computed(function(){
    var myFieldData = data.apiResponseData,
        myFieldArray = [],
        someOtherField = self.someOtherFieldSelected();
    myFieldArray.push({
        value: "any",
        label: "Any"
    });
    // some logic to push apiResponseData to myFieldArray
    return myFieldArray; //can see this array getting populated correctly
}, self);

我已经调试过,可以看到带有value / label属性的myFieldArray。 但是下拉菜单中没有显示下拉选项。

我在做ko.computed时会丢失一些上下文吗?

1 个答案:

答案 0 :(得分:-1)

如果您阅读了documentation

  

Computed observables是依赖于一个或多个其他observable的函数,并且只要这些依赖项发生任何变化,它们就会自动更新。

最好使用observableArray代替computed可观察对象。我想你的代码会像这样更好

var ViewModel = function() {
   var self = this;
   self.selectedOpt = ko.observable("");
   self.options = ko.observableArray([]);

   self.initOptions = function () {
      // you code to grab data from server
      var myFieldData = data.apiResponseData,
          myFieldArray = [],
          someOtherField = self.someOtherFieldSelected();

      self.options.push({ value: "any", label: "Any" });
   };
};
var vm = new ViewModel();

$(document).ready(function() {
  vm.initOptions();
  ko.applyBindings(vm);
});

<强> HTML

<select id="selectmyField" data-bind="options: options, value: selectedOpt">
</select>