0

Intro:

I have a simple requirement: Show or hide 1 of 2 divs depending on the value of an observable.

What I have so far:

Let's start with the html (very simple 2 divs - when 1 is visible the other one is hidden):

<div data-bind="visible: ActiveClientSideView == 'aValue'">
html content....
</div>
<div data-bind="visible: ActiveClientSideView != 'aValue'">
html content....
</div>

In my viewmodel I have the following:

self.ActiveClientSideView = ko.observable();

As well as after an Ajax call, the value gets updated:

successError: function (result) {
 if (result.Code == "INVALID_ADDRESS") {
 alert("invalid address"); 
 self.ActiveClientSideView = "AddressRecommendations";
                         }

The alert is in there to check if the code is firing, which it is.

What I would expect is the divs to show / hide as easily as updating the value of ActiveClientSideView what am I missing?

EDIT (LATEST INFO):

When the page initially loads, I can set the value of the observable in the init routine, and the visibility adjusts correctly, it is on subsequent (post page load events) , such as button clicks, or later on that the visibility does not dynamically adjust.

JL.
  • 78,954
  • 126
  • 311
  • 459
  • Have a look at the debug techniques here http://stackoverflow.com/questions/9261296/any-good-techniques-to-debug-template-binding-faults-for-knockout-js. In particular try outputting your model to a textbox and see what you get. – Ben Thurley Feb 18 '14 at 11:26
  • Seems like `ActiveClientSideView` isn't observable, which makes bindings unable to be in sync with its value. – patryk Feb 18 '14 at 11:29

2 Answers2

4

You should use ActiveClientSideView() instead ActiveClientSideView in your visible binding:

<div data-bind="visible: ActiveClientSideView() == 'aValue'">
<div data-bind="visible: ActiveClientSideView() != 'aValue'">

Update

I've added a jsfiddle demo. All works correct.

You have bug in ajax call, also. You incorrect assign value to ActiveClientSideView.

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • I thought that was the case too, I'll update the question with my latest findings. But no, this isn't the solution. – JL. Feb 18 '14 at 11:23
0

Since ActiveClientSideView is an observable, instead of:

self.ActiveClientSideView = "AddressRecommendations";
// no longer an observable and Knockout cannot notify subscribers

You should try:

self.ActiveClientSideView("AddressRecommendations"); 
// mutating the value using the observable function - notifying subscribers

Also (as pointed out by @Alexander as well), when checking the observable value, you should invoke the function first:

<div data-bind="visible: ActiveClientSideView() == 'aValue'">
<div data-bind="visible: ActiveClientSideView() != 'aValue'">
haim770
  • 48,394
  • 7
  • 105
  • 133