我正在尝试使用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();

最佳答案

问题在于,当locations数组为空时,在构造函数的第一次运行中,output变量的值仅写入一次。要在位置更改时更新输出,可以将其转换为可计算的可观察值,如下所示:

self.output = ko.computed(function(){
    return ko.toJSON(self.locations())
});

更新的 fiddle :http://jsfiddle.net/wvgRL/4/

关于javascript - 将Knockout observableArray JSON保存到localStorage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19886444/

10-11 06:12