I'm writing a simple Backbone.js code, that create exercise based on config fetched from JSON.
The flow is now:
- Some kind of controller in my code get JSON file (by jQuery).
- I create description model (based on part of my JSON file), and an answer collections by iterating through all items in 'answers' array in JSON file, and adding them to collection.
- I create views, based on model & collection.
All of this was described and resolved in this topic
That's part of my JSON file which is configuration for an exercise.
"config": {
"id": "myWomiExercise1",
"type": "",
"numberOfSets": 0,
"numberOfPresentedAnswers": 3,
"numberOfCorrectAnswerInSet": 1,
"randomAnswers": true,
"exerciseTrueFalseType": false
},
That means, that I can have for example 30 answers in my JSON, and there will be randomly selected (by using underscore methods, probably), to show 3 (which one is correct).
I pass configuration to new View, and have access to It by adding to the view
initialize: function(options) {
this.options = options || {};
}
And than, I need to create, as my config says ("randomAnswers": true) new set of answers.
As google said me, I probably need to create a new collection using underscore methods, by combining few of them - because what I need is, set created that will have x answers presented, from which y will be correct, and x-y incorrect, and finnaly, randomized.
As chaining doesn't work with 'where', I'm wondering what is the best way of doing this? My idea, which looks pretty poor is having this in View:
randomAnswerSet: function(config) {
var correct = config.numberOfCorrectAnswerInSet;
var wrong = config.numberOfPresentedAnswers - correct;
var set = [];
set.push(
_.sample( this.collection.getCorrect(), correct )
);
set.push(
_.sample( this.collection.getWrong(), wrong )
);
this.collection = new AnswersCollection(_.shuffle(_.flatten(set)));
},
And another question, should I create a new collection, like this randomAnswerSet in View and than render this view normally? Or there are better ways of doing this?
It confuses me, because I need a control button 'new example', which will recreate collection (as everything is randomized, It should gives completly new set), but do I need to destroy old one? There will be a lot of collection when user will click a button 10 times, is it optimal?
Thanks guys for all and have a great day!