Skip to content

Commit

Permalink
Update to work with observable view models.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbest committed Oct 30, 2013
1 parent acaad18 commit 22f2e49
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
10 changes: 5 additions & 5 deletions knockout-switch-case.js
Expand Up @@ -26,24 +26,22 @@ var defaultvalue = {};
ko.bindingHandlers['switch'] = {
flags: bindingFlags.contentBind | bindingFlags.canUseVirtual | bindingFlags.noValue,
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor()),
switchSkipNextArray = [],
var switchSkipNextArray = [],
switchBindings = {
// these properties are internal
$switchIndex: undefined,
$switchSkipNextArray: switchSkipNextArray,
$switchValueAccessor: valueAccessor,
$switchDefault: ko.observable(true),
// these properties are public
$default: defaultvalue,
$else: defaultvalue,
$value: value
$else: defaultvalue
},
contexts = [];

// Update $value in each context when it changes
ko.computed(function() {
var value = ko.utils.unwrapObservable(valueAccessor());
switchBindings.$value = value;
ko.utils.arrayForEach(contexts, function(context) {
context.$value = value;
});
Expand All @@ -57,6 +55,8 @@ ko.bindingHandlers['switch'] = {
switch (node.nodeType) {
case 1: case 8:
var newContext = bindingContext.extend(switchBindings);
// Set initial value of context.$switchIndex to undefined
newContext.$switchIndex = undefined;
ko.applyBindings(newContext, node);
contexts.push(newContext);
break;
Expand Down
14 changes: 14 additions & 0 deletions spec/switchBinding.js
Expand Up @@ -218,6 +218,20 @@ describe('Binding: Switch/Case', function() {
// Switch binding defaults to "true", so the first truthy value matches
expect(testNode).toContainText("Value matched");
});

it('Should work with observable view models in Knockout 3.x', function() {
testNode.innerHTML = "<div data-bind='switch: somevalue'><div data-bind='case: 1'>Value is 1</div><div data-bind='case: $value < 5'>Value is less than 5</div></div>";
var value = ko.observable(4), vm = ko.observable({ somevalue: value });
ko.applyBindings(vm, testNode);
// initially matches second case
expect(testNode).toContainText("Value is less than 5");
// change value so it matches first case (using direct observable)
value(1);
expect(testNode).toContainText("Value is 1");
// change value so it matches no cases (using viewmodel observable)
vm({ somevalue: 10 });
expect(testNode).toContainText("");
});
}

if (ko.keySubkeyBinding || ko.punches) {
Expand Down

0 comments on commit 22f2e49

Please sign in to comment.