knockout-switch-case
knockout-switch-case copied to clipboard
$value is not an observable, so dependent knockout elements do not get updated
I had a switch on a length of an array, everything works great except that in a case $default I had a reference to $value which did not get updated in some cases. Example:
<!-- ko switch: interface.calendar.events.listShown().length -->
<!-- ko case: 0 -->
No event
<!-- /ko -->
<!-- ko case: 1 -->
One event
<!-- /ko -->
<!-- ko case: $default -->
<span data-bind="text:$value"></span> events in that period
<!-- /ko -->
<!-- /ko -->
The span value did not update in some cases. listShown is a ko.computed array with trackArrayChanges enabled, and if I removed $value and changed that to interface.calendar.events.listShown().length it would work, so I guess this is a bug because the $value is not an observable.
The fix I did in your plugin was: Adding newContext.$value = ko.observable(); Before contexts.push(newContext);
And replacing context.$value = value; With context.$value(value);
(I also did the same for the switchBindings, but I don't think it's required)
After my changes everything seemed to work perfectly.
Thank you for that plugin!
Just reading old issues here. Interesting observation. I suppose because the truthiness of
<!-- ko case: $default -->
didn't change, no re-rendering of the contents of that case block was done. And, as you say, since $value is not observable, there was nothing for you span's text binding to subscribe to.
As I wasn't aware $value was even a thing in this library I hadn't been bitten by this but I'll keep this in mind should I run into it in future.
I wonder if the shorthand syntax @mbest provided on #13 would also fall victim to this
<!-- ko switch: x -->
<!-- ko case: [1, 2, 3] -->
Does $value work in here as x changes from 1 to 2 to 3?
<!-- /ko -->
<!--/ko-->
(yes I could try in jsfiddle - it's 5 minutes before "go home" time but might try tomorrow)