所以,这有点奇怪。我正在使用 Backbone 和 Backbone.localStorage 将远程数据保存到本地存储以进行缓存。很标准的东西。
当我在整个商店上运行 localStorage.clear()
时,除了具有字符串值数组的键之外,所有值都被永久清除。它在第一次检查时被清除,但是当使用 Backbone.LocalStorage.sync('create', model);
再次保存存储时,以前的值又回到那里。
当然,如果我在 Chrome Developer Tools 中手动删除 key ,那么它就会消失并且不会重新填充。就好像 localStorage.clear()
调用仍然使用字符串数组缓存键。我已经确认它最初是在应用程序启动时清除的。
我将在编辑时在此处发布一些代码和屏幕截图,但实际上它非常标准,除了在重新填充 key 后这些值仍然存在的事实。这里有什么想法吗?
编辑:有很多有趣的代码可供查看:
收藏:
app.DiagnosisCollection = Backbone.Collection.extend({
model: DiagnosisModel,
localStorage: new Backbone.LocalStorage('diagnosis'),
save: function(model) {
Backbone.LocalStorage.sync('create', model);
}
});
型号:
app.DiagnosisModel = Backbone.Model.extend({
urlRoot: app.ApiRoot,
url: app.DiagnosisApi,
initialize: function(options) {
if(!options.query) {
throw 'query must be passed to diagnosisModel';
}
this.local = false;
this._query = options.query;
},
sync: function(method, model, options) {
var diagnosisKey = localStorage.getItem('diagnosis');
var index, diagnosisStore;
if(diagnosisKey) {
diagnosisKey = diagnosisKey.split(',');
}
index = _.indexOf(diagnosisKey, this._query);
if(index !== -1) {
diagnosisStore = localStorage.getItem('diagnosis' + '-' + diagnosisKey[index]);
}
if(diagnosisStore) {
this.local = true;
options.success(JSON.parse(diagnosisStore));
}
else {
this.local = false;
var fetchUrl = this.urlRoot + this.url + this._query;
$.getJSON(fetchUrl, function(data, textStatus) {
if(textStatus !== 'success') {
options.error();
}
options.success(data);
});
}
}
});
return app.DiagnosisModel;
完成工作的 Controller 函数:
var self = this;
// Create a new collection if we don't already have one
// The save function puts it in local storage
if(!this.diagnosisCollection) {
this.diagnosisCollection = new DiagnosisCollection();
this.diagnosisCollection.on('add', function(diagModel) {
this.save(diagModel);
});
}
var diagModel = new DiagnosisModel({
query: diagId
});
diagModel.fetch({
success: function() {
var diagView = new DiagnosisView({
model: diagModel
});
if(!diagModel.local) {
self.diagnosisCollection.add(diagModel);
}
self._switchPage(diagView);
},
error: function() {
console.error("Diag Model Fetch Failed");
Backbone.history.navigate('503', { trigger: true });
}
});
顺便说一句,localStorage.clear()
调用是在应用启动时进行的。它执行 API 调用以查看服务器上的版本是否已更改。如果版本已更改,那么我们将 nuke localStorage。
最佳答案
代替 localStorage.clear()
,使用:
localStorage.removeItem('userInfo');
我在主干应用程序中遇到了同样的问题,我用这种方式清除了值。
P.s:是的,您需要一个一个地指定所有本地存储变量..:(.. 但这很有效。
关于javascript - 清除后,localStorage 会记住以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974926/