使用knockout映射发出映射数组

时间:2014-04-09 10:03:22

标签: knockout.js

我有从SIGNALR中的HUB返回的以下对象,我想将它映射到一个对象,用作淘汰赛中的viewModel。

[{"Aprover":{"CurrentTask":null,"UserID":3,"MembershipKey":"admin","Name":"admin","StartCurrentTask":null,"TotalWorkSeconds":0},"Comments":[],"Creator":{"CurrentTask":null,"UserID":3,"MembershipKey":"admin","Name":"admin","StartCurrentTask":null,"TotalWorkSeconds":0},"ParentTask":null,"Project":null,"Steps":[{"StepDescription":"sdfsdfsdfsdf","StepID":1,"IsComplete":false,"IsValidated":false}],"TaskCategory":null,"UserAssigned":{"CurrentTask":null,"UserID":3,"MembershipKey":"admin","Name":"admin","StartCurrentTask":null,"TotalWorkSeconds":0},"ID":5,"Date":null,"Priority":0,"Title":"sdfsdf","Description":"","UnitTestName":null,"Status":0,"StepsText":"sdfsdfsdfsdf\n","StatusText":"Active"},{"Aprover":{"CurrentTask":null,"UserID":3,"MembershipKey":"admin","Name":"admin","StartCurrentTask":null,"TotalWorkSeconds":0},"Comments":[],"Creator":{"CurrentTask":null,"UserID":3,"MembershipKey":"admin","Name":"admin","StartCurrentTask":null,"TotalWorkSeconds":0},"ParentTask":null,"Project":null,"Steps":[{"StepDescription":"dfgdfg","StepID":2,"IsComplete":false,"IsValidated":false}],"TaskCategory":null,"UserAssigned":{"CurrentTask":null,"UserID":3,"MembershipKey":"admin","Name":"admin","StartCurrentTask":null,"TotalWorkSeconds":0},"ID":6,"Date":null,"Priority":0,"Title":"dfdd","Description":"","UnitTestName":null,"Status":0,"StepsText":"dfgdfg\n","StatusText":"Active"}]

我用它来自动映射:

Tasks = ko.mapping.fromJSON(res) 

res =上面的对象;

问题是无论我尝试什么,任务总是一个空对象,所以我没有得到一个数组。

额外注意

如果我想向返回的对象添加方法怎么办?换句话说,我想用自定义方法扩展数组,如bellow

  var TaskListModel = function (data) {
        self = this;
        self.Items = ko.observableArray();
        if (data != null) {
            ko.mapping.fromJS(data, {}, this);
        }

        self.selectedTask = ko.observable(null);
        self.selectedID = ko.observable(-1);

        self.selectTask = function (p) {
            if (self.selectedID() == p.ID())
                self.selectedID(-1); //Hide on click
            else
                self.selectedID(p.ID());
            self.selectedTask(p);
        }; //Create the select method

我尝试映射到items属性但问题仍然存在,我完全没有想法。

1 个答案:

答案 0 :(得分:0)

看起来JSON中的换行符(\n)存在问题。我不确定它是映射插件还是其他东西,但是如果你摆脱了JSON中的\n,那么映射插件工作正常。我查了一下:

var tasks = ko.mapping.fromJSON(res);
alert(tasks().length);

请记住,任务将是一个observableArray,因此如果要检查它,必须“执行”它以获取底层数组。

以下是使用JSON的完整示例,但没有换行符:

http://jsfiddle.net/psteele/dKK55/