TheMook
TheMook

Reputation: 1541

(JsFiddle) Knockout observable shows different value in binding on screen to console.log

During investigation for another problem, I've discovered a really weird phenomenon where a <span> bound to an observable shows "true" whereas clicking a button that runs a function to log it to the console window shows "false"!

Fiddle is here: http://jsfiddle.net/fbc0w39w/1/

Click on green button, use F12 in chrome to show console window, click on "log it" and see "true" in the console. You'll also see "true" just below the submit button. Then clear down the text in user login, click elsewhere (value updates on blur) and see the error message on the login box. The value below the submit button stays as true. Click on "log it" button again and voila! It logs "False" as it should do.

Both values are coming from the vo.isValid variable as far as I can tell...?

Upvotes: 0

Views: 68

Answers (1)

user3297291
user3297291

Reputation: 23372

This might be the problem: in your getData function, you're replacing the entire validatedObservable with a new one. The two bottom UI elements are bound to the old one's isValid observable.

I'm not sure what the "right" way of using the validationObservable is (never used it), but you can see that it's a problem by nesting it in an observable:

self.vo = ko.observable(ko.validatedObservable());

self.getData = function() {
  self.selectedUser(ko.mapping.fromJS(data, validationMapping));
  self.vo(ko.validatedObservable(self.selectedUser(), {deep: true, live: true, observable: true}));
}; 

So you'd probably want to find a way to make sure the validatedObservable just reacts to changes in selectedUser without instantiating new ones.

Here's a "working" fiddle: http://jsfiddle.net/st5e0r1o/

Upvotes: 1

Related Questions