Search code examples
knockout.jstreeviewpushko.observablearray

knockoutjs pushing nested data into in array


I've been staring at my attempt to build a treeview for a while now but cant seem to get on the right track.

can anybody give me a clue where i screwed up?

HTML

<ul data-bind="foreach: reservations">
    <li><span data-bind="text: name "></span>   
        <ul data-bind="foreach: studios">
            <li><span data-bind="text: name "></span>
                <ul data-bind="foreach: times">
                    <li>T:<span data-bind="text: name "></span></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

JS

function Date(d) {
    var self = this;
    self.name = ko.observable(d.name)
    self.studios = ko.observableArray(ko.utils.arrayMap(d.studios, function(s){
        return new Studio(s);
    }));
}

function Studio(d) {   
    var self = this;
    self.name= ko.observable(d.name);
    self.times= ko.observableArray(ko.utils.arrayMap(d.times, function(i){
        return new Time(i);
    }));
}

function Time(d) {
    var self = this;
    self.id = ko.observable(d.id);
    self.name = ko.observable(d.name);    
}

function ViewModel(data) {

    var self = this;

    self.reservations = ko.observableArray();

    self.addReservation = function() {
        self.reservations.push(
            new Date({
                name: '22-12-2012',
                studios: [new Studio({
                                name: 'Studio 1',
                                times: [new Time({
                                            id: 's1_20',
                                            name: '20 uur' })]                                            
                        })]
            })
        );
    }
}



ko.applyBindings(new ViewModel());

FIDDLE http://jsfiddle.net/marsmania00/adcvs/4/


Solution

  • You tried to construct your objects twice. First in addReservation(), then in the constructors when filtering the arrays.

    If you remove the constructor-calls in the addReservation() function, it works fine.

    Modified version: http://jsfiddle.net/MizardX/adcvs/6/