0

I am trying to write a bit of UI that allows the user to either enter a number via a textbox or pick an option from a drop down.

I have made a simplified jsFiddle at http://jsfiddle.net/unklefolk/PNQeR/2/

As you can see:

  • When "The number" is selected you can enter a text into a textbox.
  • When "The option" is selected you can select one of two options from a drop down

The textbox and the drop down are BOTH bound to the ItemValue property of item in the viewModel. Although the code seems to be working I am getting errors. If you fire up the debug window in Chrome, when you change the first drop down you get the error:

Uncaught TypeError: Object 0 has no method 'ItemName'

I believe this is happening in the ItemText dependentObservable (aka computed).

    this.ItemText = ko.dependentObservable(function () {
        return _isItemAConstant() === 'true' ? this.ItemValue() : this.ItemValue().ItemName();
    }, this);

Clearly the ItemName() function is being called on the numeric value '0' causing the error.

What can I do so that this error does not occur? Is my design of binding two controls to the same observable a fundamental error?

Mark Robinson
  • 13,128
  • 13
  • 63
  • 81

1 Answers1

1

You change _isItemAConstant to false before setting the item to an object that has the ItemName property. As soon as you set it, your dependentObservable gets run and tries to evaluate the ItemName() observable which doesn't exist. You can either check for the existence of the ItemName property or use the throttle extender to delay computation until all changes are made:

this.ItemText = ko.dependentObservable(function () {
    return _isItemAConstant() === 'true' ? this.ItemValue() : this.ItemValue().ItemName();
}, this).extend( { throttle: 1} );

this.ItemText2 = ko.computed(function() {
    return this.ItemValue().ItemName ? this.ItemValue().ItemName() : this.ItemValue();
}, this);
Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113