使用带有选项绑定的计算

时间:2018-02-18 22:04:52

标签: javascript knockout.js

我尝试将computed对象与options绑定一起使用,但computed仅在文档加载时调用(而不是每次单击按钮时) )。但是,当我用一个简单的函数替换computed时,它按预期工作 - 在每个项目创建时调用该函数。

差异的原因是什么?给出here给出的答案让我觉得他们应该表现得一样,但显然他们不是。为什么呢?

代码(或fiddle):



var ViewModel = function() {
    var self = this;
    self.items = ko.observableArray([]);
    self.toggler = false;
    self.allowedOptions = ["A", "B", "C"];
    self.availableOptions = ko.computed(function() {
      var allowedOptions = self.allowedOptions.slice();
      self.toggler = !self.toggler;
      if (self.toggler) {
        return allowedOptions.splice(2, 1);
      }
      return allowedOptions;
    });
    self.createItems = function () {
      self.items.push({});
    }
}

vm = new ViewModel()
ko.applyBindings(vm);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>  
   <button data-bind="text: 'create a dropdown', click: createItems"></button>
   <div data-bind="foreach: items">
      <select data-bind="options: $parent.availableOptions,
                         optionsText: $data,
                         value: $data"></select>
   </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

首次点击KO vector,然后#include <iostream> #include <vector> using namespace std; int main() { int row = 0; cout << "Enter the size of a magic square: "; cin >> row; while (cin.fail() || row < 3 || row > 15 || (row % 2) == 0) { cout << "Please enter an odd number within the bounds of 3 and 15.\n" << endl; cout << "Enter the size of a magic square: "; cin >> row; } vector< vector<int> > square_matrix(row, vector<int>(row)); // Do something with vector... return 0; } 内的computed发生变化。你的observable中没有computed,所以它只会在第一时间触发。

通过更改observables并在computed中翻转computed的值,修改了您的示例,经过修改,以便点击每个按钮点击observable。< / p>

&#13;
&#13;
self.toggler()
&#13;
self.createItems()
&#13;
&#13;
&#13;

更新以更全面地解释

KO缓存var ViewModel = function() { var self = this; self.items = ko.observableArray([]); self.toggler = ko.observable(false); self.availableOptions = ko.computed(function() { if (self.toggler()) { return ["C"]; } return ["A", "B", "C"]; }); self.createItems = function() { self.items.push({}); self.toggler(!self.toggler()); } } vm = new ViewModel() ko.applyBindings(vm);函数的结果,并且在<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <div> <button data-bind="text: 'create a dropdown', click: createItems"></button> <div data-bind="foreach: items"> <select data-bind="options: $parent.availableOptions, value: $data"></select> </div> </div>函数内的computed发生更改之前不会对其进行重新评估。