ko.computed property to determine visibility not working

前端 未结 3 1972
死守一世寂寞
死守一世寂寞 2021-01-23 07:38

In my KncokoutJS ViewModel, I have the follow computed property:

self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.s         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-23 08:34

    Because you are not binding to a variable but to an expression, you need to add parenthesis here:

    
                                   //^^ here
    

    See the following snippet

    function CreateVM() {
        var self = this;
        this.isTrue = ko.observable(false);
        this.selectedUser = ko.observable();
        this.isLoaded = ko.observable();
        self.SelectedUserHasRoles = ko.computed(function () {
           if (self.isLoaded()) {
              return self.selectedUser().roles().length > 0;
           }
           return false;
        });
    }
    
    var vm = new CreateVM();
    ko.applyBindings(vm);
    
    var userWithRoles = { roles: ko.observableArray([1,2]) }; 
    var userWithoutRoles = { roles: ko.observableArray([]) }; 
    vm.selectedUser(userWithoutRoles);
    vm.isLoaded(true);
    
    
      
      

    User has no Roles.

    SelectedUserHasRoles:

    See user3297291's answer for more details.

提交回复
热议问题