我需要在Javascript中创建智能对象/函数,以便与我的AngularJS应用程序一起使用。我该用什么图案来做这个呢?我目前正在使用我研究过的通用JavaScript‘模块’模式,但我想知道是否应该用AngularJS方式来建模这些对象/函数(如下所示)。也许是“服务”?
我来自Java背景,这让我有点不习惯用助手方法调用对象'service.‘.’但是,我可能需要调整JavaScript/AngularJS的定义。
该应用程序是一个基本的评分系统。两个主要目标/职能如下:
LessonScoreCard
/*
* 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]
}发布于 2013-10-14 23:59:23
aet是对的,但我会进一步扩大服务的作用。服务和指令是在角上构建应用程序时的两个主要构建块。
指令与视图紧密耦合。它们用于:
服务与视图非常不耦合。它们是用来:
因此,只要服务与视图无关,服务就可以做任何事情。我认为您应该将lessonScoreCard和answerKey模块编写为服务工厂,并将它们插入到任何需要访问其功能的指令中。
https://stackoverflow.com/questions/19370796
复制相似问题