I am stumped as to what is causing the problem here as this binding handler normally works fine (below)
ko.bindingHandlers.buttonGroupChecked = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = valueAccessor();
var newValueAccessor = function() {
return {
click: function() {
value(allBindingsAccessor.get('val'));
}
};
};
ko.bindingHandlers.event.init(element, newValueAccessor,
allBindingsAccessor, viewModel, bindingContext);
},
update: function(element, valueAccessor, allBindingsAccessor,
viewModel, bindingContext) {
if (allBindingsAccessor.get("val") === ko.unwrap(valueAccessor())) {
helpers.activeClassSingle(element, "btn-info", "btn-success");
}
}
};
I keep getting an error at line 7 value(allBindingsAccessor.get('val')); saying value is not a function?
The options are defined in my viewmodel as follows:-
self.yesNoOptions = [
{val: 1, text: "Yes"},
{val: 0, text: "No"}
];
And the corresponding HTML and binding is:-
<div class="btn-group btn-group-justified" data-bind="foreach: $root.yesNoOptions">
<div class="btn btn-lg btn-info" data-bind="buttonGroupChecked: $root.currentVariation().variationAgreed, val: val, text: text"></div>
</div>
Where $root.currentVariation().variationAgreed is an item that is currently selected and is an observable as part of the following object.
var observableWorkItemVariation = function(data){
var self = this;
data = data || {};
self.id = ko.observable(data.id || "");
self.orderWorkItemID = ko.observable(data.orderWorkItemID || "");
self.variationAgreed = ko.observable(data.variationAgreed || 0);
self.changeWorkBillable = ko.observable(data.changeWorkBillable || 1);
self.declareBillable = ko.observable(data.declareBillable || 0);
self.changeWorkBillable.subscribe(function(val){
if(self.changeWorkBillable() == 0){
self.declareBillable(0);
}
});
self.changeWorkPayable = ko.observable(data.changeWorkPayable || 1);
self.variationCode = ko.observable(data.variationCode || "");
}
It is correctly highlighting the selected item (No as it is defaulted to 0) but when I try to change it throws the error.
It looks like
valueis out of scope when theclickeven is fired.As it stands now you're defining
valuein the local scope of one function and you're then trying to access it later in the local scope of a different function.I'd recommend using
clickbinding directly on each div. Knockout will automatically pass you an instance of the ViewModel that was clicked, so you can use that inside of the click handler on the $root view model to figure out which button was clicked to make it active.