javascript - is it valid for a subscribe callback function to make use of a computed observable -


i have made jsfiddle illustrate problem having:

http://jsfiddle.net/gt8d2mub/

var model = {     a: ko.observable(false),     b: ko.observable(false),     c: ko.observable(false),     data: ko.observable(''),     isvalid: function () {         return this.a() && this.b() && this.c();     } };  model.alltrue = ko.computed(function () {     return this.a() && this.b() && this.c(); }, model);  model.query = ko.computed(function () {     return 'a = ' + this.a() + '; b = ' + this.b() + '; c = ' + this.c() + ';'; }, model);  model.query.subscribe(function () {     if (this.isvalid()) {         // load data...           this.data(this.query());     }     else {                 this.data('no value');      }  }, model);  ko.applybindings(model); 

the model has 3 boolean observables; a, b , c. computed observable (alltrue) calculates if true. computed observable (query) summary of a, b, , c.

if manually subscribe "query" intention of loading data, first check "alltrue", "alltrue" may not yet updated , correct, because procedure update value happens after callback fires.

for example, check a, b, c , callback called before computed "alltrue" calculated.

is trying abnormal, or there way work?

perhaps there no advantage using computed, , indeed, if replace normal function (isvalid) behaviour expect. intend have other things react alltrue/isvalid value, , thought use computed in such scenarios (a normal function work, thought there advantages using computed there).

if query isn't valid unless terms available, it's better push evaluation query observable tighten dependencies:

http://jsfiddle.net/gt8d2mub/1/

var model = {     a: ko.observable(false),     b: ko.observable(false),     c: ko.observable(false),     data: ko.observable('') };  model.alltrue = ko.computed(function () {     return this.a() && this.b() && this.c(); }, model);  model.query = ko.computed(function () {     return this.alltrue() ?          'a = ' + this.a() + '; b = ' + this.b() + '; c = ' + this.c() + ';'        : null; }, model);  model.query.subscribe(function (query) {     if (!query) {         this.data('no value');          return;     }     // load data...     this.data(query);     }, model);  ko.applybindings(model); 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -