我正在尝试使用ko.toJSON方法将observableArray保存到localStorage.在第一页加载时,我的应用程序将从服务器接收JSON对象并填充observableArray.我想将它存储在localStorage中以进行优化和离线使用,但是ko.toJSON正在返回[],即使其中有明显的数据.
我能够在jsFiddle重现这个问题
HTML
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();
最佳答案
问题是当位置数组为空时,输出变量的值只在构造函数的第一次运行时写入一次.要更新位置更改的输出,可以将其转换为计算的observable,如下所示:
原文链接:https://www.f2er.com/js/429841.htmlself.output = ko.computed(function(){
return ko.toJSON(self.locations())
});
更新的小提琴:http://jsfiddle.net/wvgRL/4/