I'm making a quiz. I'm loading in the questions from a json file. The models have a 'use: ' attribute. I'm filtering the collection by use and plucking the IDs, then I'm getting a random ID for the question and setting use to false once it has been answered. In this way, a user will go through all the questions in a random order with no repeats. I'd like to keep track of the used questions for each user and when they have done them all reset the question bank.
I'm using backbone.dualstorage and it worked once and then I tried to reset the collection by going through each model and destroying it. Now I can't seem to repopulate the local collection with models because the remote models have the same IDs as the destroyed model IDs.
How can I re-add all the models in the remote collection to localStorage again?
//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();
});
}
}
Here's the fiddle: http://jsfiddle.net/robertocarroll/10xqvk18/10/
Thanks!
Turns out backbone.dualstorage was overkill. I accessed localStorage directly instead:
Here's the fiddle: http://jsfiddle.net/hcqse7j4/3/