2

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.

5
  • Could you please supply some more code (i.e. ViewModel definition) Commented Jul 31, 2012 at 19:58
  • It is enormous by now. I will figure out a fiddle to showcase the problem in a few minutes =) Commented Jul 31, 2012 at 20:00
  • @MaximV.Pavlov It needs to be observable for the visisble property to update when it changes. Putting it in JSON will not work. Commented Jul 31, 2012 at 20:02
  • I've updated the question body to include the fiddle that can showcase the problem. Thanks in advance for looking at it. Commented Jul 31, 2012 at 20:19
  • 1
    @MaximV.Pavlov That fiddle is insane. My previous comment stands, it won't update because HasValue is not observable. Commented Jul 31, 2012 at 20:50

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jason. My understanding was that it would work the way I set it up, since even though .HasValue wasn't an observable, dialogSelectedCode was indeed, and that entire value was actually changing every time drop box item is selected. Now I know it doesn't work that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.