I’ve found out (thanks to the KO forum) that for computed observables, it’s not possible to chain writes like this:
viewModel.someComputed(20).otherComputed(100).someObservable('hi')
and this bummed me because I have many observables which I want to extend() – and so they will become computed, and so I have to remove all the chained calls.
So I’ve made this small change in the dependantObservable() function (just added: return this;)
function dependentObservable() {
if (arguments.length > 0) {
set.apply(dependentObservable, arguments);
return this;
} else {
return get();
}
}
And now I can chain writes!
My question is: what’s the downside of doing this?
I assume there is one, because this wasn’t implemented 😛
Thanks,
Uri G
There won’t be any issues. First, all code that was written before your change assumed that computed observables aren’t chainable and thus no one would use the value returned by a setter. Second, all places where the return value is used are calling getter.
In other words all legacy code looks like
Without chaining this code:
would throw a type error. So the only case to worry about is
which currently always returns
undefined. And as for me it looks like a rather bogus code since there are much better ways to set some variable toundefined.So if you want chainig go with this change.
Because in most traditional languages (Java, C#, C++, PHP) chaining is usually an exception rather than a norm. In JavaScript world only a few libraries use chaining heavily like jQuery, Underscore and d3. Most other libraries including Knockout don’t rely on it, though.
Also Steve Sanderson could have just forgotten to put chaing support for computed observables. Send him a suggestion 😉