How to organize your model and achieve encapsulation in a single page web application

First, I apologize for not knowing. I am very pleased when it comes to JavaScript, mainly based on the Java background, so for me it is quite a bit. I read a few posts, but to be honest, I'm not even sure about a good question.

I follow β€œOne Page Web Application: JavaScript from End to End,” and now I go back through the code and try to restore / reorganize it so that it makes sense to me.

One thing I would like to understand is to properly organize the code using the modular template referenced by the author.

spa.model = (function () {
    var people,
        stateMap = { id : 1 };

    people = (function () {
        var methods1, method2;

        method1 = function(){ … }; // do something
        method2 = function(){ … }; // do something 

        return {
            method1 : method1,
            method2 : method2
        };
    }());

    return {
        people : people
    };

}());

This allows me to call something like spa.model.people.method1 ();

, var , .

spa.model = (function () {
    var people = spa.model.people,
        stateMap = { id : 1 };

    return {
        people : people
    };

}());

spa.model.people = (function () {
    var method, method2;

    method1 = function() { return stateMap.id; },
    method2 = ... ;

    return {
        method1 : method1,
        method2 : method2
    };

}());

, , . , stateMap spa.model.people.

? ( ) spa.model . , 20 . .

+4
2

IMO, - ( "" ) , model.people, model.auth model.chat. ( "" ) . (model.people, model.auth, model.chat) .

, 3 (model.people, model.chat, model.auth) stateMap. , stateMap, . , , , , .

model = (function () {
  var 
    __undef,
    configMap = {};
    stateMap  = { 
      user_id   : __undef,
      chatee_id : __undef
    },

    logIn, addPerson, rmPerson, callPerson, hangUp;

  logIn = function ( user_name, passwd_str ) {
    user_id = model.auth( user_name, passwd_str );
    if ( user_id ) {
      model.people.addPerson( user_id ):
      model.chat.announceUser( user_id );
      stateMap.user_id = user_id;
    } 
  };

  // ... and more methods that coordinate subordinate modules

  return { 
    logIn      : logIn,
    addPerson  : addPerson,
    rmPerson   : rmPerson,
    callPerson : callPerson,
    hangUp     : hangUp
  };
}());

. , . : "" , - , . . . , , TODO, , .

, - TODO. , . , .

, !

+2

-. , - :

(function () {

  spa.model = {

    stateMap: {
      id: 1
    },

  };


  var people = {

    method1: function() {
      return stateMap.id;
    },

    method2: function(){},
  };

  spa.model.people = people; 

  // obviously expose spa at the end.
  window.spa = spa;

}());
+1

Source: https://habr.com/ru/post/1523965/


All Articles