I have problem with checked and click binding.
I want to have check-listbox for selection multiple rows, and I want to be able to reject unselect last value.
The best what i can get is this.
There is problem, that when i click the last checkbox it will not unselect, but checked binding will still remove the last value from array.
Please help with any solution.
HTML:
<div id="bookingResources" class="listcontrol">
<!-- ko foreach:resources -->
<div class="li" data-bind="css:{ 'selected':$root.isResourceSelected($data) }">
<a href="#" data-bind="click:$root.selectResource">
<span data-bind="text:Name"></span>
<input class="right" type="checkbox" data-bind="click:$root.checkboxClick, clickBubble:false, value:Id, checked:$root.resourceIds"/>
</a>
</div>
<!-- /ko -->
</div>
JS:
var model = function(){
var self = this;
self.resources = [{"Id":4612,"Name":"John"},{"Id":4613,"Name":"Tom"},{"Id":4614,"Name":"Marty"}];
self.resourceIds = ko.observableArray([4612]);
self.isResourceSelected = function(resource) {
return self.resourceIds.indexOf(resource.Id) >= 0;
}
self.selectResource = function (resource) {
if (self.isResourceSelected(resource)) {
if (self.resourceIds().length > 1) { // the last not remove
self.resourceIds.remove(resource.Id);
}
} else {
self.resourceIds.push(resource.Id);
}
}
self.checkboxClick = function(resource) {
if (self.resourceIds().length != 1)
return true;
return self.resourceIds()[0] != resource.Id;
}
//subscribe
self.resourceIds.subscribe(function(newValue) {
console.log("Selected resorces (" + newValue.length + "): " + newValue);
});
}
ko.applyBindings(new model(), document.getElementById("bookingResources"))
Ok, I searched through the knockout source code of checked binding and found, that it is simply binding click event HERE.
So i needed only jquery to stop eventPropagation on the checkbox element.
Calling event.stopimmediatepropagation()
should do the work.
Together I can stop event propagation, so checked binding will not process current click:
self.checkboxClick = function(resource, event) {
if (self.resourceIds().length != 1)
return true;
if(self.resourceIds()[0] == resource.Id)
{
event.stopImmediatePropagation();
return false;
}
return true;
}