[英]How can I implement MVVM with offline storage and Knockout.js?
I can implement Mvvm with Knockout.js. 我可以用Knockout.js实现Mvvm。 But I want to use it with cross browser(FF and Chrome) supported Html 5 offline storage.
但我希望将它与跨浏览器(FF和Chrome)支持的Html 5离线存储一起使用。
I want to bind html objects to offline storage. 我想将html对象绑定到脱机存储。
I haven't tried it, but there is a knockout.localStorage
project on GitHub , that seems to be what you are looking for. 我没有尝试过,但是在GitHub上有一个
knockout.localStorage
项目 ,这似乎是你在寻找的。
With that plugin, you should be able to pass an object as a second argument, when you create your observable, which saves the observable into localStorage. 使用该插件,您应该能够在创建observable时将对象作为第二个参数传递,从而将observable保存到localStorage中。
From the documentation: 从文档:
var viewModel = {
name: ko.observable('James', {persist: 'name'})
}
ko.applyBindings(viewModel);
You can use a library such as amplify.js which can serialize objects to localStorage (cross browser). 您可以使用诸如amplify.js之类的库,它可以将对象序列化为localStorage(跨浏览器)。 It falls back to older storage tools for older browsers too.
它也适用于旧版浏览器的旧版存储工具。 First, unwrap the observables to a JSON object, then use amplify.store to serialize the object and store it.
首先,将observable展开到JSON对象,然后使用amplify.store来序列化对象并存储它。 Then you can pull it back out and map it back to an observable object when you want to fetch it.
然后,当您想要获取它时,可以将其拉出并将其映射回可观察对象。
http://amplifyjs.com/api/store/ http://amplifyjs.com/api/store/
I worked out a solution bases on the subscribe
feature of KnockoutJS. 我根据KnockoutJS的
subscribe
功能制定了一个解决方案。 It takes a model and persist all the observable
properties. 它需要一个模型并保留所有
observable
属性。
ko.persistChanges = function (vm, prefix) {
if (prefix === undefined) {
prefix = '';
}
for (var n in vm) {
var observable = vm[n];
var key = prefix + n;
if (ko.isObservable(observable) && !ko.isComputed(observable)) {
//track change of observable
ko.trackChange(observable, key);
//force load
observable();
}
}
};
Check http://keestalkstech.com/2014/02/automatic-knockout-model-persistence-offline-with-amplify/ for code and JSFiddle example. 检查http://keestalkstech.com/2014/02/automatic-knockout-model-persistence-offline-with-amplify/以获取代码和JSFiddle示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.