hardywang
hardywang

Reputation: 5192

When does a dependentObservable's function get called?

I have following sample code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
   <script type="text/javascript" src="../knockout-1.2.1.js"></script>
   <script type="text/javascript" src="../knockout.mapping.js"></script>
</head>
<body>
   <div>Nested Object Value1 <input data-bind="value: NestedObject.Value1" type="text" /></div>
   <div>Value2 <input data-bind="value: Value2" type="text" /></div>

<hr/>
<div data-bind="text: ko.toJSON(viewModel)"></div>

<script type="text/javascript">
   var initialData = {"NestedObject":{"Value1":"Dummy value"}, "Value2" : "Hello world"};

   var viewModel = ko.mapping.fromJS(initialData);

   viewModel.ParameterUpdatedDependentObservable = ko.dependentObservable(function() {
        alert("dependentObservable fired");
    }, viewModel);

   ko.applyBindings(viewModel); // Makes Knockout get to work
   </script>
</body>
</html>

What I expected is that to see a popup to alert value is changed by user. When I run it, the popup shows up only once when page is initially loaded. Afterwards I can make value update but alert is no long triggered.

Any clue why?

Upvotes: 0

Views: 801

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

dependentObservables track the observables that have their values accessed during evaluation to create dependencies.

In your case, your dependentObsevable does not access any observables. If you access the value of one or more of your observables in your code, then you will see it trigger whenever any of its dependencies are updated.

Upvotes: 3

Related Questions