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

前端 未结 3 1920

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条回答
  •  梦毁少年i
    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());
    

提交回复
热议问题