please help me in understanding why this computed observable is not able to access observables.

前端 未结 3 1826

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

Not sure why computed observable is not returning any value. I know how to make it working but not sure why t

相关标签:
3条回答
  • 2021-01-01 06:31

    object literals are quite simple to create, which makes them awesome. But this is one of the reasons I prefer using functions to create view models. With an object literal you could just extend the view model and create the computed ... or with the function you can do it all in one function statement, as @RPNiemeyer points out.

    Another option is to use the revealing module pattern, which 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);​
    
    0 讨论(0)
  • 2021-01-01 06:44

    In addition to the solution from @RPNiemeyer, there is yet 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 makes sure the computed will only be called when needed, because at creation time the viewModel variable won't be ready.

    0 讨论(0)
  • 2021-01-01 06:48

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

    A couple alternatives:

    -Create it outside of your initial 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 a 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());
    
    0 讨论(0)
提交回复
热议问题