Sunday, December 29, 2013

Knockout Computed Observables


F = C * 9/5 + 32

Knockout with its computed observables can track related dependencies, so if one changes, the other also changes automagically. Ember has a similar thing with .property syntax, but struggles with multiple dependencies.

var C = ko.observable(0);
var F = ko.computed( function() {
   return C() * 9/5 + 32;
});

Angular however with its dirty checking has no way of knowing if either one changes, so recomputes the function below if any property on $scope changes.

$scope.C = 0;
$scope.F = function() {
  return $scope.C * 9/5 + 32;
}

Here Angular does not know that the property F which is a function, is dependent on property C.
So with dirty checking Angular actually goes and recomputes this value anytime anything changes on $scope, even if it is not C or F. So it is wasted computing if you look at it this way.

Note: ES6 Harmony could change all this once observable properties are added to browser capabilities natively.