chris
chris

Reputation: 4867

change observable value from knockoutjs model

I think it is a easy thing... I have a knockoutjs viewmodel like this:

UserModel = function(user) {
    // ...
    this.Permissions = new PermissionsModel(user.Permissions);
    this.fullAccessValue = ko.observable(false);


    // if the permissions change
    $.each(self.Permissions, function(i, item) {
        item.subscribe(function() {
            if (self.allStoresSelected() && self.allPermissionsSelected()) {
                userModel.fullAccessValue = ko.observable(true);
                $('#savFullAccessCheck').prop('checked', true);
            } else {
                userModel.fullAccessValue = ko.observable(false);
                $('#savFullAccessCheck').prop('checked', false);
            }
        });
     });

};

What I have to do:
I have a list with checkboxes (permissions) and another checkbox (fullaccess). Now, when all permission-checkboxes are checked, the fullaccess have to be checked. If not all checked, the fullAccess have to be unchecked.

Otherwise, when I check the fullAccess checkbox, all other checkboxes have to be cheked.

The permissions for the checkboxes looks like this:

var PermissionsModel = function(permissions) {
    var self = this;
    self.Access1 = ko.observable(permissions.Access1);
    self.Access2 = ko.observable(permissions.Access1);
    // ...
};


userModel = new UserModel();
ko.applyBindings(userModel, $('#savBottomWrap')[0]);

In short words: My Problem is how to update the observable values with javascript!?

This not really works:

userModel.fullAccessValue = ko.observable(false);
$('#savFullAccessCheck').prop('checked', false);

Upvotes: 1

Views: 116

Answers (2)

Anders
Anders

Reputation: 17554

I helped another fellow with this, you need to use a computed

http://jsfiddle.net/AneL9/

self.SelectAll = ko.computed({
    read: function() {
        var item = ko.utils.arrayFirst(self.People(), function(item) {
            return !item.Selected();
        });
        return item == null;           
    },
    write: function(value) {
        ko.utils.arrayForEach(self.People(), function (person) {
            person.Selected(value);
        });
    }
});

knockoutjs deselect/select all checkboxes when one or more items deselected

Upvotes: 2

Alex Filatov
Alex Filatov

Reputation: 2321

if it implemented here

userModel.fullAccessValue = ko.observable(false);

than you can chenge value like below:

userModel.fullAccessValue(true);

EDIT: And you should bind this value to checkbox like that

<input type="checkbox" checked="data-bind: userModel.fullAccessValue">

Upvotes: 1

Related Questions