Knockout.JS映射到observable与observableArray

时间:2013-04-19 03:05:45

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

我无法弄清楚为什么当我带回一个数组(使用'foreach'绑定)时我的ko.mapping正常工作,但是当它是一个单个对象时(使用'with'绑定)它不会什么都不用。我没有收到任何错误,但我也没有得到任何结果:

function EventViewModel() {
    var self = this;
    self.events = ko.observableArray([]);
    self.singleEvent = ko.observable({});

    self.getEvents = function () {
        self.events.removeAll();
        $.ajax("/api/Event/", {
            contentType: "application/json",
            success: function (allData) {
                ko.mapping.fromJS(allData, null, self.events);
            }
        });
    }    
    self.getSingleEvent = function () {
        self.events.removeAll();
        $.ajax("/api/Event/?guid=435a666b-7913-417f-a474-dfb33d74c2ec", {
            contentType: "application/json",
            success: function (allData) {
                ko.mapping.fromJS(allData, null, self.singleEvent);
            }
        });
    }

    self.getEvents();
    self.getSingleEvent();
};
window.vm = new EventViewModel();
ko.applyBindings(vm);

我可以将getSingleEvent()的结果推送到数组中并再次使用'foreach':

ko.mapping.fromJS([allData], null, self.singleEvent);

并使singleEvent成为一个observableArray,它确实有效,但对我来说这似乎是一种骗局。

getEvents()的JSON如下所示:

[{"EventId":4,"Year":2013,"StartDate":"2013-08-28T00:00:00","EndDate":"2013-09-02T00:00:00","EventGuid":"435a666b-7913-417f-a474-dfb33d74c2ec"},{"EventId":5,"Year":2013,"StartDate":"2013-06-07T00:00:00","EndDate":"2013-06-09T00:00:00","EventGuid":"615014ba-15cd-4371-8d43-04d66eb558a2"}]

,getSingleEvent()中的JSON如下所示:

{"EventId":4,"Year":2013,"StartDate":"2013-08-28T00:00:00","EndDate":"2013-09-02T00:00:00","EventGuid":"435a666b-7913-417f-a474-dfb33d74c2ec"}

1 个答案:

答案 0 :(得分:1)

我很确定ko.mapping不会使对象可观察到。相反,它使对象的每个属性都可以观察到。另一方面,没有什么能阻止你只是做self.singleEvent(allData)来设置observable。