【问题标题】:Mapping hard coded data with server side generated data using knockout mapping使用敲除映射将硬编码数据与服务器端生成的数据进行映射
【发布时间】:2015-06-03 07:18:41
【问题描述】:

here 显示的代码是 RP Niemeyer 的 knockout-sortable.js 示例的修改版本,由 lossleader 作为答案 here 创建。

这是一个数据模型如下..

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);
};

连续数据如下..

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

数据在vm中初始化如下..

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

但是当从服务器获取数据并使用knockout-mapping.js..映射到knockout viewmodel时,我所做的事情如下..

    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
    };

在这种情况下,我无法弄清楚要从服务器发送的 json 的必要数据结构..

真诚感谢任何帮助..

谢谢

【问题讨论】:

  • 尝试创建数据传输对象并发送可枚举的表列表。每个表都具有此处所需的属性。对于学生,请尝试发送字符串/对象数组。
  • @chromio 你能否说明我尝试在表上添加 ko.tojson 的 Table obj 的示例结构,它甚至不显示 id、maxstudents 和 allowedstudentgender。除非我知道如何发送数据的结构..,一旦我知道我可以使用 DTO 或其他东西发送它..

标签: knockout.js knockout-2.0 knockout-mapping-plugin


【解决方案1】:

用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 2013-08-14
    • 2017-05-01
    • 2012-04-13
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多