SteveSanderson / knockout-es5

Knockout.js meets ECMAScript 5 properties
158 stars 39 forks source link

Functions as computed #36

Open SimonFarrugia opened 9 years ago

SimonFarrugia commented 9 years ago

Hi, I just discovered this library on Steve Sanderson's blog today and it looks really neat. Though I haven't tried playing around with it yet, from reading the blog post I think I might have a good suggestion regarding functions and computed.

In my opinion, unlike properties the primary use of functions is not to output a value but rather to execute some logic/task (Ex. save changes) which may not necessary return anything. Thus, automatically converting all functions to computed observables is not always desirable nor a correct approach. On the other hand since we have getters/setters for properties in es5, a property get function could easily be converted to a computed.

Example:

var order = {
     item : "Product",
     price : 99.9,
     quantity : 2,

     //ko.track converts subtotal getter to computed
     get subtotal () {
         return "$" + (this.price * this.quantity).toFixed(2);
     },

     //No need for ko.track to convert buy function to computed
     buy : function(){
         //Execute purchase logic
     }
}

ko.track(order);

I hope you find my suggestion helpful. Keep up the good work.

archangel-irk commented 9 years ago

Thank you very much for the offer. I definitely will study it in detail.

jmvtrinidad commented 7 years ago

Hi @archangel-irk , Is there already solution for this. Thanks.