我需要在 Javascript 中创建智能对象/函数以与我的 AngularJS 应用程序一起使用。我应该为此使用什么模式?我目前正在使用我研究过的通用 JavaScript“模块”模式,但我想知道是否应该以 AngularJS 方式对这些对象/函数(如下)进行建模。也许作为“服务”?
我来自 Java 背景,这让我有点不舒服将带有辅助方法的对象称为“服务”。但我可能需要调整我对 JavaScript/AngularJS 的定义。
该应用程序是一个基本的评分系统。两个主要对象/功能如下:
课程记分卡
/*
* LessonScoreCard
*
* Is a "module" that keeps track of the score a user has for a given lesson
* and whether or not for a given question there are more correct answers
* that can be made.
*/
var lessonScoreCard = (function() {
//Map of questions to scores
var privateQuestionNumberToScoreMap = {};
//API to be used by external clients
var publicAPI = {
//A public function utilizing privates
setScore: function(questionNumber, score) {
privateQuestionNumberToScoreMap[ questionNumber ] = score;
},
//Sum the total score
getTotalScore: function( ){
var totalScore = 0;
for( var questionNumber in privateQuestionNumberToScoreMap ){
totalScore += privateQuestionNumberToScoreMap[questionNumber];
}
}
};
return publicAPI;
})();
答案键
/*
* AnswerKey
*
* Is a "module" that takes an answer key and performs functions
* related to it.
*/
var answerKey = (function() {
//Set of right answers
var privateQuestionNumberToAnswerArrayMap;
//API to be used by external clients
var publicAPI = {
setAnswerKey: function(answerKeyModel) {
privateQuestionNumberToAnswerArrayMap = answerKeyModel;
},
// A public function utilizing privates
isCorrect: function(question, answer) {
var isCorrect = false;
var answerArray = privateQuestionNumberToAnswerArrayMap[ question ];
if (answerArray.indexOf(answer) !== -1) {
isCorrect = true;
}
return isCorrect;
},
getAnswerCount: function( question ){
var answerArray = privateQuestionNumberToAnswerArrayMap[ question ];
return answerArray.length;
}
};
return publicAPI;
})();
示例 JSON 答案密钥模型
{
1: [1, 3],
2: [4]
}