0
votes

I basically have an observable array in my ViewModel

self.details=ko.observableArray([]);

which holds an array of model - DetailModel which has an isChecked property as an observable.

I want to subscribe to changes to isChecked and remove all other checkbox checks.

for(var i=0;i<10;++i)
{
    var detail=new DetailModel(i);

    detailList.push(detail);
    detail.isChecked.subscribe(function(checkBoxCheckedState){

    if(checkBoxCheckedState==true)
    {
      /* Idea is to untick all other checkboxes if one is checked */
      console.log(detail);
      console.log(detailList);
      ko.utils.arrayFilter(self.details(), function(detailRow) {
          if(detailRow.id!=detail.id)
          {
              detailRow.isChecked(false);
          }
      });
    }
});

I am initializing the details array inside a loop and attaching the subscribe there, because of closure, only the last detail object is available inside the subscribe function.

How can I achieve the same without passing callback to parent / parent model reference inside child view model?

https://jsfiddle.net/7srbxu5y/17/

1

1 Answers

1
votes

Do you really need isChecked in the detail model? Could you consider using just one selected property in the parent view model instead? In this case your child models would not have to know anything about parent viewmodel. See sample code

function DetailModel(name) {
   this.name = name;
}

function ViewModel(items) {
    this.items = ko.observableArray(items);    
    this.selected = ko.observable();
}

ViewModel.prototype.select = function select(data) {
   var selected = this.selected.peek();
   if (selected !== data) {
        this.selected(data);
   } else {   
        this.selected(null);
   }
   return true;
}

Working fiddle