Please help me understand why this computed observable cannot access observables.

this is a fiddle - http://jsfiddle.net/iRamesh/36N4m/

I do not know why computed observation does not return any value. I know how to make it work, but I don’t know why the current code does not work. please, help

+4
source share
3 answers

computed observables are evaluated immediately upon creation. In your case, viewModel has not yet been created, so this causes an error.

A couple of alternatives:

-Create it outside your source object literal:

 var viewModel = { firstName: ko.observable("r"), lastName: ko.observable("j"), }; viewModel.fullName = ko.computed(function() { return viewModel.firstName(); }); 

-Create your view model in function:

 var ViewModel = function() { this.firstName = ko.observable("r"); this.lastName = ko.observable("j"); this.fullName = ko.computed(function() { return this.firstName(); }, this); }; ko.applyBindings(new ViewModel()); 
+11
source

object literals are pretty easy to create, which makes them awesome. But this is one of the reasons I prefer to use functions to create representation models. With an object literal, you can simply extend the view model and create a computed ... or with a function that you can do in a single function statement, as @RPNiemeyer points out.

Another option is to use the expansion module template that I like best: http://jsfiddle.net/johnpapa/36N4m/1/

 var viewModel = (function() { var firstName = ko.observable("r"), lastName = ko.observable("j"), fullName = ko.computed(function() { return firstName(); }); return { firstName: firstName, lastName: lastName, fullName: fullName } })(); ko.applyBindings(viewModel);​ 
+7
source

In addition to the solution from @RPNiemeyer, there is another alternative:

 var viewModel = { firstName: ko.observable("r"), lastName: ko.observable("j"), fullName: ko.computed({ read: function() { return viewModel.firstName(); }, deferEvaluation: true }) }; 

The computed callback refers to the viewModel variable from the outer scope, and deferEvaluation ensures that the computed deferEvaluation will only be called if necessary, because the viewModel variable viewModel not be ready at creation time.

+3
source

Source: https://habr.com/ru/post/1396765/


All Articles