knockout.js - Updating one observableArray while looping another observableArray -
given 1 observablearray, populated service call, used render checkbox list in view:
orgchart = ko.observablearray();
- id
- dept
and observablearray, populated service, returns list of id's departments have been selected (in db) above array.
selecteddepartment = ko.observablearray();
- id
how knockout bind second array when looping on first?
i tried this, renders checkbox list, fails update selecteddepartment array.
<div data-bind="foreach: orgchart"> <div><input type="checkbox" data-bind="checked: selecteddepartment, value: id }"/><span data-bind="text: dept"/></div> </div>
i'm guessing need use mapping or computed value, can't find examples.
my solution have 1 observablearray, not two.
combine data received 2 service calls list of objects.
for example,
var orgchart = getdatafromfirstservicecall(); var selecteddepartments = getdatafromsecondservicecall(); var vm = { departments = ko.observablearray(), } function department( id , name ) { this.id = id; this.name = name; this.selected = selecteddepartments.indexof(id) !== -1; } for( var = 0; < orgchart.length; i++ ) { var dept = orgchart[i]; vm.departments.push( new department( dept.id , dept.name ); } ko.applybindings( vm );
now in html can this:
<div data-bind="foreach: departments"> <div> <input type="checkbox" data-bind="checked: selected }" /> <span data-bind="text: name"/> </div> </div>
edit:
to send data server, loop through departments array , grab ones selected
flag set true
var departments = vm.departments(), selected = []; for( var = 0; < departments.length; i++ ) { var dept = departments[i]; if( dept.selected ) selected.push(dept); }
voila!
or if want save bandwidth and/or delete/insert statements db, can make selected
observable, subscribe it's changes , save server individually.
function department( id , name ) { var self = this; self.id = id; self.name = name; self.selected = ko.observable( selecteddepartments.indexof(id) !== -1 ); self.selected.subscribe(function(newvalue) { // save newvalue database // perform ajax post, sending self.id , newvalue }); }
Comments
Post a Comment