我正在做一个测验。我正在从 json 文件中加载问题。这些模型有一个“使用:”属性。我正在按使用过滤集合并提取 ID,然后我得到问题的随机 ID,并在回答后将 use 设置为 false。这样,用户将以随机顺序完成所有问题,没有重复。我想跟踪每个用户使用过的问题,并在他们完成所有问题后重置问题库。
我正在使用backbone.dualstorage,它工作了一次,然后我尝试通过遍历每个模型并销毁它来重置集合。现在我似乎无法用模型重新填充本地集合,因为远程模型具有与被破坏模型 ID 相同的 ID。
如何再次将远程集合中的所有模型重新添加到 localStorage?
//Question collection
var PlayCollection = Backbone.Collection.extend({
model: PlayModel,
url: "https://raw.githubusercontent.com/robertocarroll/barjeel-app/master/app/data/questions.json",
//when I set remote it works without local at all
//remote: function () {return true;}
});
//define new question collection
var newCollection = new PlayCollection();
// load data
newCollection.fetch({
success: function (newCollection, response, options) {
console.log("fetch questions success");
//this shows all the question IDs which I destroyed
console.log(newCollection.destroyedModelIds());
//this is empty
console.log(newCollection.dirtyModels());
}
});
function getQuestion() {
var theQuestions = newCollection.dirtyModels()[0].collection;
//get the IDs of all questions which haven't been used
var questions = theQuestions.chain()
.filter(function (m) {
return m.get('use')
})
.pluck('id')
.value();
console.log(questions);
if (questions.length > 0) {
// get random ID from question ID array
var rand = questions[_.random(questions.length - 1)];
console.log('chosen ID value: ' + rand);
//get a model from a collection, specified by ID
var currentQuestion = theQuestions.get(rand);
console.log(currentQuestion);
//set the status of that question to used
currentQuestion.set("use", false);
}
//if there's not more questions
else {
console.log("No more questions");
//delete models in local
_.chain(newCollection.models).clone().each(function (model) {
console.log('deleting model ' + model.id);
model.destroy();
});
}
}
这是小提琴:http: //jsfiddle.net/robertocarroll/10xqvk18/10/
谢谢!