lundi 15 avril 2019

Binding predefined state to checkboxes using ko.js

I want to apply predefined states to checkboxes using knockout.js I've already tried dozens of things, but cant get this working.

This is my code:

function DemoItem(id, name, state) {
  var self = this;

  self.id = ko.observable(id);
  self.Name = ko.observable(name);
  self.Selected = ko.observable(state);
}

function ViewModel() {
  var self = this;

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


  self.init = function() {
    self.availableItems.push(new DemoItem(1, 'One', true));
    self.availableItems.push(new DemoItem(2, 'Two', true));
    self.availableItems.push(new DemoItem(3, 'Three', false));
    self.availableItems.push(new DemoItem(4, 'Four', true));
    self.availableItems.push(new DemoItem(5, 'Five', true));
  };

  self.relayState = ko.computed({
    read: function() {
      ko.utils.arrayForEach(self.availableItems, function(item) {
        return item.Selected();
      });

    },
    write: function(value) {
      if (value) {
        console.log("associate item ");
      } else {
        console.log("disasociate item ");
      }
    }
  })
}

var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.init();
Available Items:
<div data-bind="foreach: $root.availableItems">
  <input type="checkbox" data-bind="value: id(), checked: $root.relayState" />
  <span data-bind="text: '&nbsp;' + Name()"></span>
  <br/>
</div>

I cant get checkboxes to initially apply predefined values.

This is the link to JSfiddle: http://jsfiddle.net/w392rpxf/




Aucun commentaire:

Enregistrer un commentaire