Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

KnockoutJS json object/observable "visible" binding not working

I am trying to configure a rather complex model to bind a view to using KnockoutJS.

Here is a problem markup section:

<input type="text" data-bind="visible: dialogSelectedCode.HasValue, value: dialogSelectedCodeValue"/>
<span data-bind="text: ko.toJSON(dialogSelectedCode)"></span>

input element is never shown, but my "debug" span shows the contents

{"Code":"{intInc_G}","HasValue":true}

What is the correct way to bind a visible of my input in case the "decision"-data is hidden inside JSON object?

UPDATE: Here is a rather complex fiddle of the problem. To get to the problem dialog, run the fiddle, click "Add block" and try choosing several items in the drop down input (especially first and the second one - since they clearly show that dialogSelectedCode variable is indeed being updated.

Upvotes: 2

Views: 1749

Answers (1)

Jason Goemaat
Jason Goemaat

Reputation: 29234

I think you need to create a computed for the HasValue property. Your binding dialogSelectedCode.HasValue does not follow the observable, it checks for the HasValue on the observable function. The property way dialogSelectedCode().HasValue throws an error. Creating a computable and letting it do the tests works:

self.dialogSelectedCodeHasValue = ko.computed(function() {
    var selectedCode  = ko.utils.unwrapObservable(self.dialogSelectedCode);
    return selectedCode && selectedCode.HasValue;
});

Upvotes: 2

Related Questions