Search code examples
knockout.jsknockout-2.0knockout-mapping-plugin

Mapping hard coded data with server side generated data using knockout mapping


The code shown here is an modified version of an example of knockout-sortable.js by RP Niemeyer and created by lossleader as an answer here.

Here is a data model as follows..

var Table = function(id, name, students,maxstudents,allowedstudentgender) {
    this.students = ko.observableArray(students);
    this.students.id = id;
    this.name = ko.observable(name);
    this.students.maxstudents=ko.observable(maxstudents);
    this.students.allowedstudentgender= ko.observableArray(allowedstudentgender);
};

The consecutive data is as follows..

    var initialTables = [
        new Table(1,"Table One",  [
           new Student(3, "Jim", "male"),
             new Student(6, "Chase", "male")
        ],2,["male"])
//and so on..
    ];

The data is initialised in the vm as follows..

var SeatingChartModel = function(tables, availableStudents) {
    var self = this;
    this.tables = ko.observableArray(tables);

But when the data is brought from the server and mapped to the knockout viewmodel using knockout-mapping.js.., what I do is something as follows..

    var SeatingChartModel = function() {
            var self = this;
            this.tables = ko.observableArray();
    // more stuff happens here..and then..

     $.get('/api/gettables', function (data) {
        self.tables(ko.mapping.fromJS(data)()); // for jtoken
              OR
        self.tables(ko.mapping.fromJS(JSON.parse(data))()); // for json
    };

I'm unable to figure out the necessary data structure of the json to be sent from server in this case..

Any help is sincerely appreciated..

Thanks


Solution

  • Solved it by using arraymap..

    this.tables = ko.observableArray();
        var temptables= ko.utils.arrayMap(dataFromServer, function(item) {
        return new Table(item.id,item.name, item.students, item.maxstudents, item.allowedstudentgender);
            });
            this.tables(temptables);