Binding a list of objects to a list of checkboxes

前端 未结 1 1508
温柔的废话
温柔的废话 2020-12-14 05:42

I have a list of objects, each with a few fields, like this:

function Person(id,name,age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

va         


        
1条回答
  •  孤城傲影
    2020-12-14 06:16

    You can do something like:

    With this kind of ViewModel:

    var viewModel = {
        people: ko.observableArray(listOfPeople),
        selectedPeople: ko.observableArray()
    };
    

    The value attribute controls what the checked binding adds/removes from an array when it is bound against an array. You could also write a dependentObservable that populates the array with the actual objects, if necessary.

    Live Example:

    function Person(id,name,age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    var listOfPeople = [
        new Person(1, 'Fred', 25),
        new Person(2, 'Joe', 60),
        new Person(3, 'Sally', 43)
    ];
    
    var viewModel = {
        people: ko.observableArray(listOfPeople),
        selectedPeople: ko.observableArray([1])
    };
    
        
    ko.applyBindings(viewModel);

    0 讨论(0)
提交回复
热议问题