Knockout computed write not firing

时间:2015-06-26 10:02:04

标签: javascript jquery checkbox knockout.js

I have a simple grid, with checkable rows.

Each row represents basically this object:

function Person(name, isChecked, isDisabled) {
        this.name = name;
        this.isChecked = ko.observable(isChecked);
        this.isDisabled = ko.observable(isDisabled);
    };

There's also a check all checkbox in the grid header, which should check all the non-disabled rows or un-check them (depending on the state). This should also work the other way around, meaning that when I check all the rows within the grid (clickin on each row's checkbox), the header checkbox should be checked.

The problem is, the computed bound to the check all checkbox fails to execute.

See this example: http://jsfiddle.net/eww5dn8q/.

Notice that when you check them all, the alert within the write function is executed. However, when you uncheck, it no longer works.

Consider this version where I comment the if statement (lines 30 and 32): http://jsfiddle.net/qws3f7js/.

In this version, it seems to run well whether it's check or uncheck, but at the cost of not taking into account the disabled rows.

I'm pretty sure there's a minor thing I'm missing there..

1 个答案:

答案 0 :(得分:1)

比照。评论问题: '错误'确实很小。稍微修改计算的read函数就可以了(再加上它将if else子句简化为if):

  read: function () {
      var isAllSelected = true;
      $.each(self.myData(), function(i, person){
          if(!person.isChecked() && !person.isDisabled()){
              isAllSelected = false;
          }
      });
      return isAllSelected;
  },

见小提琴: http://jsfiddle.net/kevinvanlierde/eww5dn8q/1/