Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs: how to recover from or trap a missing ko.observable() or ko.computed()

Tags:

knockout.js

BACKGROUND

Trevor has a simple knockoutjs page with three declared ko.observable() and one declared ko.computed()

PROBLEM

Trevor would like to remove the third declared item. The problem is, when Trevor removes it, the rendering of all subsequent declared items fails as well.

EXAMPLE

Consider the following code fragment:

<p>r1c1:    <input data-bind="value: r1c1, valueUpdate:'afterkeydown'" /></p>
<p>r1c2:    <input data-bind="value: r1c2, valueUpdate:'afterkeydown'" /></p>
<p>r1c3:    <input data-bind="value: r1c3, valueUpdate:'afterkeydown'" /></p>
<p>r1c4:    <input data-bind="value: r1c4, valueUpdate:'afterkeydown'" /></p>

<script type="text/javascript">
  var ViewModel = function(){
    var self    =   this;

    self.r1c1 = ko.observable('alpha');
    self.r1c2 = ko.observable('bravo');
    self.r1c4 = ko.observable('delta');

    // if Trevor comments out this line, it caues r1c4 to stop rendering
    // this is expected, but is there a workaround that does not require to
    // remove the data-binding to value r1c3 from the HTML body ?
    self.r1c3 = ko.computed(function(){return [self.r1c1(),self.r1c2()].join(':')});
  }

  ko.applyBindings(new ViewModel());
</script>

QUESTION

Is there a way that Trevor can comment out the ko.computed() declaration for r1c3 and still leave the data-binding to r1c3 in the page body; without it breaking the subsequent data-binding to r1c4?

like image 962
dreftymac Avatar asked Dec 21 '25 16:12

dreftymac


1 Answers

One trick that Trevor can use is to reference the variable in the binding as $data.r1c3 rather than just r1c3. Referencing an undefined property of an object does not cause an error like referencing an undefined variable would.

So, Trevor would want to make his HTML look like:

<p>r1c3:    <input data-bind="value: $data.r1c3, valueUpdate:'afterkeydown'" /></p>
like image 151
RP Niemeyer Avatar answered Dec 23 '25 08:12

RP Niemeyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!