/resources/javascript/backbone_models.js
JavaScript | 686 lines | 601 code | 53 blank | 32 comment | 70 complexity | 5e8ef3890548080386f787dc01cb9c35 MD5 | raw file
- /**
- * Created with JetBrains PhpStorm.
- * User: Minas
- * Date: 6/03/13
- * Time: 10:17
- * To change this template use File | Settings | File Templates.
- */
- $(function () {
- app = {};
- app.models = app.models || {};
- app.collections = app.collections || {};
-
- /**
- * Contains static variables.
- */
- var CONFIG = (function() {
- var private = {
- 'CONTEXT': "repository\\content_object\\assessment",
- 'TYPE': 'POST'
- };
- return {
- get: function(name) { return private[name]; }
- };
- })();
-
- app.models.QuestionType = Backbone.Model.extend({
- initialize : function() {
-
- }, defaults : {
- name : "A questiontype",
- className : "questionType",
- img : "",
- icon : "",
- iconSmall : ""
- }
- });
-
- app.models.Category = Backbone.Model.extend({
- initialize : function(){
-
- }, defaults : {
- categoryName : "Mijn repository"
- }
-
- });
-
- app.collections.Categories = Backbone.Collection.extend({
- initialize:function () {
- this.assessment_id = app.utilities.get_assessment_id();
- },
- model : app.models.Category,
- urlRoot: "/chamilo",
- url: function() {
- var xhrOptions = {};
- var base = this.urlRoot + "/ajax.php";
- return base;
- },
- sync : function(method, model, options)
- {
- options.type = CONFIG.get('TYPE');
- options.data.context = CONFIG.get('CONTEXT');
- return Backbone.sync(method, model, options);
- },
- fetchCategories : function (options)
- {
- options || (options = {});
- options.data || (options.data = {});
- options.data.method = 'get_categories';
-
- return Backbone.Collection.prototype.fetch.call(this, options, {success : function(){app.models.Question.prototype.defaults.category = categoriesCollection.at(0);}});
- },
- parse : function(response, options)
- {
- if(response.result_code == 200)
- {
- response.properties || (response.properties = {});
- response.properties.categories || (response.properties.categories = "[]");
- return JSON.parse(response.properties.categories);
- }
- else
- {
- return JSON.parse("[]");
- }
- }
- });
-
- /**
- * Collection of all QuestionTypes.
- */
- app.collections.QuestionTypes = Backbone.Collection.extend({
- initialize : function() {
- },
- model : app.models.QuestionType,
- findByClassName : function (name) {
- return this.findWhere({className : name});
- }
- });
-
- /**
- * The superModel Question, every type of question extends from this Model.
- */
- app.models.Question = Backbone.Model.extend({
- initialize:function () {
- }, defaults:{
- type: new app.models.QuestionType(),
- title:"What is the question?",
- category: new app.models.Category({id:0}),
- description: "...",
- weight : 1,
- NotEmptyAttributes : ['title', 'description', 'weight']
- },
- urlRoot: "/chamilo",
- url: function() {
- var xhrOptions = {};
- var base = this.urlRoot + "/ajax.php";
- return base;
- },
- sync : function(method, model, options)
- {
- options.type = CONFIG.get('TYPE');
- options.data.context = CONFIG.get('CONTEXT');
- return Backbone.sync(method, model, options);
- },
- save : function(attributes, options)
- {
- attributes || (attributes = {});
- options || (options = {});
- options.data || (options.data = {});
- options.data.method = 'save_question';
- options.data.class_name = this.get('type').get('className');
- var attributeKeys = {};
- if(_.isUndefined(this.get('id')))
- {
- if(!_.isUndefined(this.get('contentId')))
- {
- if(addedQuestions.where({contentId : this.get('contentId')}).length > 1)
- {
- attributeKeys = this.attributes;
- }
- else
- {
- options.data.content_id = this.get('contentId');
- }
- }
- options.data.question_identifier = 0;
- attributeKeys = this.attributes;
- options.success =
- function(model, response, options)
- {
- var contentId = parseInt(response.properties.content_id);
- if(_.isUndefined(model.get('contentId')))
- {
- var clonedModel = model.clone();
- clonedModel.set('contentId', contentId);
- allQuestionsCollection.add(clonedModel);
- }
- model.set('id', parseInt(response.properties.question_id));
- model.set('contentId', contentId);
- }
- }
- else
- {
- options.data.question_identifier = this.id;
- }
-
- for(var key in this.changes)
- {
- attributeKeys[key] = this.changes[key];
- }
- var newAttributes = {};
- for(var key in attributeKeys)
- {
- if(typeof this.get(key) == 'object' && !_.isUndefined(this['get_' + key]))
- {
- newAttributes[key] = this['get_' + key]();
- }
- else
- {
- newAttributes[key] = attributeKeys[key];
- }
- }
- options.data.assessment_id = addedQuestions.assessment_id;
- options.data.attributes = JSON.stringify(newAttributes);
- options.validate = false;
- Backbone.Model.prototype.save.call(this, attributes, options);
- },
- destroy : function(options)
- {
- if(!_.isUndefined(this.id))
- {
- options || (options = {});
- options.data || (options.data = {});
- options.data.method = 'delete_question';
- options.data.question_identifier = this.id;
- options.data.class_name = this.get('type').get('className');
- return Backbone.Model.prototype.destroy.call(this, options);
- }
- else
- {
- addedQuestions.remove(this);
- }
- },
- validate : function(attrs) {
- var notEmptyAttributes = this.get('NotEmptyAttributes');
- var errors = [];
- for(var i=0; i < notEmptyAttributes.length; i++)
- {
- var attribute = notEmptyAttributes[i];
- if(!attrs[attribute])
- {
- errors.push({name : attribute, message: 'Please fill in the ' + attribute +' field.'});
- }
- }
- if(attrs.weight && attrs.weight == 0)
- {
- errors.push({name : 'weight', message: 'Not allowed to be 0'});
- }
- return errors.length > 0 ? errors : false;
- },
- get_category : function()
- {
- return this.get('category').get('id');
- },
- set_category : function(id)
- {
- var category = categoriesCollection.get(id);
- if(!category)
- {
- category = new app.models.Category({id : id});
- categoriesCollection.add(category);
- }
- this.set('category', category);
- }
-
- });
-
- app.models.Option = Backbone.Model.extend({
- initialize:function () {
- }, defaults:{
- id:0,
- name:"",
- feedback:"",
- score:"1"
- }
- });
-
- app.models.MatchOption = app.models.Option.extend({
- initialize:function () {
- }, defaults:{
- match:"A"
- }
- });
-
- _.extend(app.models.MatchOption.prototype.defaults, app.models.Option.prototype.defaults);
-
- app.models.Match = Backbone.Model.extend({
- initialize:function () {
- }, defaults:{
- id : 0,
- match:"A",
- name:""
- }
- });
-
- app.models.NumericOption = Backbone.Model.extend({
- initialize:function () {
- }, defaults:{
- id: 0,
- tolerance:"1",
- feedback:"",
- score:""
- }
- });
-
- app.models.Item = Backbone.Model.extend({
- initialize:function () {
- },
- defaults:{
- id:0,
- possibleAnswer:"",
- tolerance:"1",
- feedback:"",
- score:""
- }
- });
- /**
- * AssessmentOpenQuestion Model
- * @method setquestion_type : sets the type of question based upon question_type_Enums
- */
- app.models.AssessmentOpenQuestion = app.models.Question.extend(
- {
- initialize:function () {
-
- },
- defaults:{
- question_type_Enums : {
- OpenQuestion : {value : 1, name: "Open question", type : "OpenQuestion"},
- OpenQuestionWithDocument : {value : 2, name: "Open question with document", type: "OpenQuestionWithDocument"},
- DocumentQuestion : {value : 3, name: "Document", type: "DocumentQuestion"}},
- question_type: "OpenQuestion",
- feedback:"",
- hint:""
- },
- set_question_type : function(value) {
- for(var typeEnum in this.get('question_type_Enums'))
- {
- if(this.get('question_type_Enums')[typeEnum].value == value)
- {
- var enumeration = this.get('question_type_Enums')[typeEnum];
- this.set('question_type', enumeration);
- break;
- }
- }
- },
- get_question_type : function() {
- return this.get('question_type').value;
- },
- get_category : function(){
- return this.get('category').get('id');
- }
- });
-
- app.models.AssessmentOpenQuestion.prototype.defaults.question_type = app.models.AssessmentOpenQuestion.prototype.defaults.question_type_Enums.OpenQuestion;
- _.extend(app.models.AssessmentOpenQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
- app.models.FillInBlanksQuestion = app.models.Question.extend(
- {
- initialize:function () {
- },
- defaults:{
- spec:"auto-sized text field",
- inputShow:"1",
- caseSensitive:"1",
- posScore:"1",
- negScore:"0",
- fieldSizeVar:"0",
- exercise:""
- }
- });
-
- _.extend(app.models.FillInBlanksQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
- /**
- * Not implemented yet
- */
- app.models.HotspotQuestion = app.models.Question.extend(
- {
- initialize:function () {
- },
- defaults:{
- img:"",
- feedback:"",
- score:"1"
- }
- });
-
- _.extend(app.models.HotspotQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
-
- app.models.AssessmentMatchingQuestion = app.models.Question.extend(
- {
- initialize:function () {
- },
- defaults:{
- option:new app.models.MatchOption(),
- match:new app.models.Match(),
- feedback:"",
- score:"1"
- }
- });
-
- _.extend(app.models.AssessmentMatchingQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
- /**
- * Similar to MatchingQuestion
- * Possibility to allow multiple matching answers
- * Different interface
- */
- app.models.AssessmentMatrixQuestion = app.models.AssessmentMatchingQuestion.extend(
- {
- initialize:function () {
- },
- defaults:{
- multipleMatches:"0"
- }
- });
-
- _.extend(app.models.AssessmentMatrixQuestion.prototype.defaults, app.models.AssessmentMatchingQuestion.prototype.defaults);
-
-
- app.models.AssessmentMultipleChoiceQuestion = app.models.Question.extend(
- {
- initialize:function () {
- },
- defaults:{
- option:new Option(),
- feedback:"",
- score:"1",
- multipleAnswers:"0",
- hint:""
- }
- });
-
- _.extend(app.models.AssessmentMultipleChoiceQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
-
- app.models.AssessmentMatchNumericQuestion = app.models.Question.extend(
- {
- initialize:function () {
- },
- defaults:{
- toleranceType:"absolute",
- hint:"",
- numericOption:new app.models.NumericOption()
- }
- });
-
- _.extend(app.models.AssessmentMatchNumericQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
-
- app.models.OrderingQuestion = app.models.Question.extend(
- {
- initialize:function () {
- },
- defaults:{
- item:new app.models.Item()
- }
- }
- );
-
- _.extend(app.models.OrderingQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
-
- app.models.AssessmentRatingQuestion = app.models.Question.extend({
- initialize:function(){
- },
- defaults:{
- min:"0",
- max:"100",
- correctValue:"",
- hint:""
- }
- });
-
- _.extend(app.models.AssessmentRatingQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
-
- app.models.AssessmentSelectQuestion = app.models.Question.extend({
- initialize:function(){
- },
- defaults:{
- option : new Option(),
- multipleAnswers:"0",
- hint:""
- }
- });
-
- _.extend(app.models.AssessmentSelectQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
-
- app.models.MatchQuestion = app.models.Question.extend({
- initialize:function(){
- },
- defaults:{
- option : new app.models.Option(),
- hint:""
- }
- });
-
- _.extend(app.models.MatchQuestion.prototype.defaults, app.models.Question.prototype.defaults);
-
- /**
- * Same name as above, think of another name
- */
- app.models.AssessmentMatchTextQuestion = app.models.MatchQuestion.extend
- ({
- initialize:function(){
- },
- defaults:{
- wildcard:"1",
- caseInsensitive:"1"
- }
- });
-
- _.extend(app.models.AssessmentMatchTextQuestion.prototype.defaults, app.models.MatchQuestion.prototype.defaults);
-
-
- app.collections.Questions = Backbone.Collection.extend({
- initialize:function () {
- this.assessment_id = app.utilities.get_assessment_id();
- },
- model : app.models.Question,
- urlRoot: "/chamilo",
- url: function() {
- var xhrOptions = {};
- var base = this.urlRoot + "/ajax.php";
- return base;
- },
- comparator : function(question)
- {
- return question.get('display_order');
- },
- addQuestion : function(question, index)
- {
- if(index)
- {
- if(index < this.length - 1)
- {
- for(var i = index; i < this.length; i++)
- {
- var movedQuestion = this.at(i);
- movedQuestion.set('display_order', i + 2);
- movedQuestion.save();
- }
- }
- }
- else
- {
- index = this.length;
- }
- question.set('display_order', index + 1);
- this.add(question, {at : index});
- },
- updateDisplayOrder : function()
- {
- for(var i=0; i < this.length; i++)
- {
- if(this.at(i).get('display_order') !== (i+1))
- {
- this.at(i).set('display_order', i+1);
- this.at(i).changes['display_order'] = this.at(i).get('display_order');
- this.at(i).save();
- }
- }
- },
- sync : function(method, model, options)
- {
- options || (options={});
- options.type = CONFIG.get('TYPE');
- options.data.context = CONFIG.get('CONTEXT');
- return Backbone.sync(method, model, options);
- },
- parse : function(response, options)
- {
- if(response.result_code == 200)
- {
- response.properties || (response.properties = {});
- response.properties.questions || (response.properties.questions = "[]");
- return JSON.parse(response.properties.questions);
- }
- else
- {
- return JSON.parse("[]");
- }
- },
- fetch : function (options)
- {
- options || (options = {});
- options.data || (options.data = {});
- options.data.method = 'get_questions';
- options.data.assessment_identifier = this.assessment_id;
- options.success = function(collection, response, options) {
- var questions = collection.parse(response, options);
- collection.reset();
- for(var i=0; i <questions.length; i++)
- {
- var question = addedQuestions.create_question(questions[i]);
- collection.add(question);
-
- }
- };
- return Backbone.Collection.prototype.fetch.call(this, options);
- },
- fetchAll : function (options)
- {
- options || (options = {});
- options.data || (options.data = {});
- options.data.method = 'get_all_questions';
- options.success = function(collection, response, options) {
- var questions = collection.parse(response, options);
- collection.reset();
- for(var i=0; i <questions.length; i++)
- {
- var question = allQuestionsCollection.create_question(questions[i]);
- if(question)
- {
- collection.add(question, {silent : true});
- }
- }
- allQuestionsView.listenTo(collection,'change reset add remove', allQuestionsView.render);
- allQuestionsView.render();
- //makeDraggable();
- };
- return Backbone.Collection.prototype.fetch.call(this, options);
- },
- create_question : function(attributes)
- {
- if(!_.isUndefined(attributes.className))
- {
- if(!_.isUndefined(app.models[attributes.className]))
- {
- if(!_.isUndefined(attributes.description))
- {
- attributes.description = _.unescape(attributes.description);
- }
- var question = new app.models[attributes.className]();
- for(var key in attributes)
- {
- if(question.get(key) && typeof question.get(key) == 'object' && !_.isUndefined(question['set_' + key]))
- {
- question['set_'+key](attributes[key]);
- }
- else
- {
- if(isNaN(attributes[key]) || _.isEmpty(attributes[key]))
- {
- question.set(key, attributes[key]);
- }
- else
- {
- question.set(key, parseInt(attributes[key]));
- }
- }
- }
- question.set('type', questionTypeCollection.findByClassName(attributes.className));
- question.unset('className');
- question.changes = {};
- if(_.isUndefined(attributes.title))
- question.set('title', question.get('type').get('name'));
- return question;
- }
- }
- },
- destroy_questions : function(questions, options)
- {
- options || (options = {});
- options.data || (options.data = {});
- options.data.method = 'delete_questions';
- var questionsAjax = new Array();
- var j = 0;
- for(var i=0; i < questions.length; i++)
- {
- var question = questions.at(i);
- if(!_.isUndefined(question.get('id')))
- {
- questionsAjax[j] = new Array(2);
- questionsAjax[j][0] = question.get('id');
- questionsAjax[j][1] = question.get('type').get('className');
- j++;
- }
- this.remove(question);
- }
- if(questionsAjax.length > 0)
- {
- options.data.questions = JSON.stringify(questionsAjax);
- return this.sync('delete',this, options);
- }
- },
- getTotalWeight : function()
- {
- var total = 0;
- for(var i=0; i < this.length; i++)
- {
- total += this.at(i).get('weight');
- }
- return total;
- },
- divideTotalWeight : function(totalWeight)
- {
- var modulus = totalWeight % this.length;
- var weight = (totalWeight - modulus) / this.length;
-
- for(var i = 0; i < this.length; i++)
- {
- var question = this.at(i);
- if(question.get('weight') != weight)
- {
- question.changes || (question.changes = {});
- question.set('weight', weight);
- question.changes.weight = weight;
- question.save();
- }
- }
- }
- });
- });