我正在尝试使用 ko.toJSON 方法将 observableArray 保存到 localStorage。在第一页加载时,我的应用程序将从服务器接收 JSON 对象并填充 observableArray。我想将它存储在 localStorage 中以进行优化和离线使用,但是 ko.toJSON 正在返回 [] 即使其中有明显的数据。
我可以在这个jsFiddle重现这个问题
HTML
<span data-bind="text: locations().length"></span>
<div data-bind="foreach: locations">
<div>
<span data-bind="text: title"></span>
<span> </span>
<span data-bind="text: timeZone"></span>
</div>
</div>
<pre data-bind="text: output"></pre>
JavaScript
var dataFromServer = [
{name: "Cleveland", zone: "EST"},
{name: "Chicago", zone: "CST"},
{name: "New York", zone: "EST"}
];
var MyNS = window.MyNS || {};
MyNS.ViewModel = function () {
var self = this;
self.locations = ko.observableArray([]);
self.load = function (){
var mappedData = ko.utils.arrayMap(dataFromServer, function(item) {
return new MyNS.Location(item.name, item.zone);
});
self.locations(mappedData);
};
self.output = ko.toJSON(self.locations());
self.execute = function(){
self.load();
ko.applyBindings(self);
};
};
MyNS.Location = function (t, z) {
this.title = t;
this.timeZone = z;
};
var model = new MyNS.ViewModel();
model.execute();