knockout / tko

🥊 Technical Knockout – The Monorepo for Knockout.js (4.0+)
http://www.tko.io
Other
275 stars 34 forks source link

Make pureComputed the default #23

Open brianmhunt opened 7 years ago

brianmhunt commented 7 years ago

From https://github.com/knockout/tko.computed/issues/1

From https://github.com/knockout/knockout/issues/2167 by @futpib

I'm moving this here since this is where it could be accepted (for ko-4).

Make pureComputed the default computed and make computed impureComputed or even `autorun

I find that, when choosing between pureComputed and computed, pureComputed is almost always the right one due to laziness and performance benefits.

You really want computed only when you want immediate and predictable evaluation for side-effects.

Also you almost certainly want to break your computed in two parts with ignoreDependencies to make sure evaluation happens only when you want:

ko.computed(() => {
    // register dependencies
    ko.ignoreDependencies(() => {
        // produce side-effects
    });
});

This is why I propose that computed is renamed to a longer (and scarier) impureComputed or autorun (like in mobx), possibly changing it's signature dividing "register dependencies" and "produce side-effects" parts. And pureComputed is renamed to computed to make it the go-to option for less experienced knockout.js developers. Of course this would break compatibility, so this is probably only feasible for the next major release.

If we could make documentation advise towards pureComputed and against computed when in doubt, that would be great.

If it were possible to ban any non-local mutation in pureComputed's read and write functions (except writing other observables in write), I'd also root for that.