简体   繁体   English

AngularJS使用的封装模式

[英]Encapsulation Pattern to Use with AngularJS

I need to create smart objects/functions in Javascript to use with my AngularJS app. 我需要使用Javascript创建智能对象/函数,以便与AngularJS应用程序一起使用。 What pattern should I use for this? 我应该使用哪种模式? I currently am using the generic JavaScript 'module' pattern which I researched, but I am wondering if I should be modeling these object/functions (below) in an AngularJS-way. 我目前正在使用我研究的通用JavaScript“模块”模式,但我想知道是否应该以AngularJS方式对这些对象/函数进行建模(如下)。 Perhaps as 'services'? 也许作为“服务”?

I come from a Java background which makes me a little uncomfortable calling a object with helper methods a 'service.' 我来自Java背景,这使我有点不高兴将使用辅助方法的对象称为“服务”。 But I may need to adjust my definitions for JavaScript/AngularJS. 但是我可能需要调整JavaScript / AngularJS的定义。

The app is a basic grading system. 该应用程序是一个基本的评分系统。 The two main objects/functions are below: 以下是两个主要的对象/功能:

LessonScoreCard 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;
})();

Answer Key 答案键

/* 
 * 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;

})();

Sample JSON Answer Key Model 样本JSON答案密钥模型

    {
        1: [1, 3],
        2: [4]
    }

aet is right, but I would expand the role of services even further. aet是正确的,但我将进一步扩大服务的作用。 Services and directives are your two primary building blocks when constructing an app on top of Angular. 在Angular上构建应用程序时,服务和指令是您的两个主要构建块。

Directives are tightly coupled to the view. 指令与视图紧密耦合 They are for: 它们用于:

  1. Changing some data in response to user input or action 根据用户输入或操作更改某些数据
  2. Updating the UI in response to a change in data 更新UI以响应数据更改

Services are very uncoupled from the view. 服务与视图之间是非常分离的。 They're for: 他们是为了:

  1. Encapsulating business logic 封装业务逻辑
  2. Storing more robust model data that you want to share throughout your app, especially if your app is so large that it has more than 1 controller, or if your model data is tightly coupled to a persistence mechanism (eg a Backbone model ) 存储要在整个应用程序中共享的更可靠的模型数据,尤其是当您的应用程序太大而具有多个控制器时,或者模型数据与持久性机制紧密耦合(例如,骨干模型 )时,尤其如此

So services can really do or be anything, as long as that thing isn't view-related. 因此,服务实际上可以做任何事情,或者可以做任何事情,只要该事情与视图无关即可。 I think you should write your lessonScoreCard and answerKey modules as service factories, and inject them into any directives which need access to their functionality. 我认为您应该将lessonScoreCard和answerKey模块编写为服务工厂,并将它们注入需要访问其功能的任何指令中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM