The meaning of the MVC

  • What do three MVC objects do
    • M stands for model, which encapsulates data related to the application’s business logic and how it is processed, and is listened to by one or more views. The model notifies the views concerned whenever the model’s data changes.

    • V stands for view, which represents the current state of the Model, and everything that should be seen by the user belongs to V. As the model’s data changes, the view gets the opportunity to refresh itself accordingly.

    • C stands for controller. It defines the response mode of user interface to user input, plays an organizational role among different levels, and is used to control the flow of application program. It deals with user behavior and changes in data model.

  • According to MVC theory, all programs can be decomposed into three objects M, V and C.

eventBus

  • What is eventBus and what does it do
    • EventBus can be used to customize events. It can be used to monitor and trigger customized events to realize communication between objects. When data or certain features change, it can automatically listen for events to make some changes. Implementing eventBus is very simple using the jQuery library, which has built-in apis for listening on and triggering events
  • For example, a simple code for addition, subtraction, multiplication, and division: render the data after it has changed, calling render()
add(){
	data++;
	render(data);
},
minus(){
	data--;
	render(data);
},
mul(){
	data*=2;
	render(data);
},
div(){
	data/=2;
	render(data);
},
Copy the code
  • Using eventBus to simplify, the Render () function is automatically called whenever data is updated
       const eventBus = $({})
       const m = {
            data: {
                n: 100
            },
            updata(data) {
                Object.assign(m.data, data)
                eventBus.trigger('n:updataed')}}const v = {
            render(){}}const c = {
            init() {
                eventBus.on('n:updataed'.() = > {
                    v.render(m.data)
                })
            },
            add() {
                m.updata(m.data.n + 1)},minus() {
                m.updata(m.data.n - 1)},multiply() {
                m.updata(m.data.n * 2)},divide() {
                m.updata(m.data.n / 2)}}Copy the code

Table driven programming

  • Using table driven methods, you can write if-else and switch-case more elegantly

    • Code summary:

    Table driven is a scheme that looks up information from tables without using logical statements (if and case). In fact, anything that can be selected by logical statements can be selected by looking up tables. For simple cases, using logical statements is easier and more straightforward. But as logical chains become more complex, look-up tables become more attractive.

  • For example, to get the current date:

    const date = new Date(a)const day = date.getDay()
    if (day === 0) {
        console.log('It's Sunday.')}else if (day === 1) {
        console.log('It's Monday.')}...else{
        console.log('It's Saturday')}Copy the code

Use the if… Else or switch seven times. The code is much cleaner if the data is stored in an array:

    const week = ['Sunday'.'Monday'.'Tuesday'. ]const date = new Date(a)const day = date.getDay()
    const today = week[day]
Copy the code
  • The meaning of table driven programming lies in the separation of logic and data.

For example, grading is based on scores:

    function level(score){
        if (score < 60) {
            return 'poor'
        } else if(score < 80) {
            return 'good'
        } else if(score < 99) {
            return 'best'}}Copy the code

This simple code works, but the logic needs to be modified whenever you need to add one or more levels, such as 60 to 70 or a perfect score.

Using table drivers:

    function level(score) {
        const levelTabel = {
            60: 'poor'.80: 'good'.90: 'best'.100: 'perfect'
        }
        const key = Object.keys(levelTable)
        const len = key.length
        for (let i in levelTable) {
            if (parseFloat(score) <= i) {
                return levelTable[i]
            }
        }
        return levelTable[key[len - 1]]}Copy the code

As many levels as you need to add, you can simply add tables without changing the logic.

JS modular development

The following article is excerpted from: link

  • Modularization is a key way for the development of a language, it can help developers split and organization code, with the development of the front-end technology, front-end code quantity is becoming more and more big, you need to have very good management code, and modularization can help developers solve naming conflicts, rely on management, improve the readability of the code, code decoupling and improve the reusability of the code.

    • Modular development is actually packaging details, provide the use of interface, each other do not affect each other, each module is to achieve a specific function, but also need to avoid the pollution of global variables, initially through the function to achieve the module, in fact, is the use of the local scope of the function to form a module
        function fn1(){}
        function fn2(){}
    Copy the code
    • The above fn1 and fn2 functions respectively form two modules, which can be directly called when needed, but this can not guarantee that variable name conflicts with other modules, and there is no direct relationship between module members, and then there is the use of objects as modules, the members are placed in the object.
        var nameModule={
            name:0,
            fn1:function(){},
            fn2:function(){}
        }
    Copy the code
    • Before the modularity specification, developers often used the Module design pattern to solve the problem of Js global scope contamination. The Module pattern was originally defined as a way to provide private and public encapsulation for classes in traditional software engineering. In JavaScript, the Module pattern is encapsulated using anonymous function self-calls to build closures, and distinguishes between private and public members through custom exposure behavior.
        var nameModule = (function() {
        var moduleName = "module";  // Private attributes
    
        function setModuleName(name) {
            moduleName = name;
        }
    
        function getModuleName() {
            return moduleName;
        }
        return { 
            setModuleName: setModuleName, 
            getModuleName: getModuleName
        }
    })();
    
    console.log(nameModule.getModuleName()); // module
    nameModule.setModuleName("nameModule");
    console.log(nameModule.getModuleName()); // nameModule
    Copy the code
  • CommonJs, AMD, CMD and ES6 are all specifications used in the definition of modularity, in order to standardize the introduction of modules, deal with dependencies between modules and solve naming conflicts, and use modularity scheme to decompose complex systems into manageable modules with more reasonable code structure and higher maintainability.

  • ES6 implements module functions at the level of language standards to become a common module solution for browsers and servers. ES6 uses export and Export Default to export modules, and imports modules using Import. In addition, in the browser environment, it is possible to use require to import modules exported by export and export default, but it is still recommended to use the standard import module import. Currently, ES6 modules are static and cannot be loaded on demand. You can parse them using Babel or CommonJS require, and a new specification proposal is likely to incorporate dynamic loading into the standard. Export and export default have the following differences:

    • Export can be imported on demand, but export default cannot.
    • There can be multiple export, but only one export default.
    • Export can export variable expressions directly, export default cannot.
    • If the export mode is used, add {} in the import mode. Export default is not required.
    // Export a single feature
export letName1 name2,... , nameN;// also var, const
export letName1 =... , name2 =... ,... , nameN;// also var, const
export function FunctionName(){... }export class ClassName {... }// Export the list
export { name1, name2, …, nameN };

    // Rename the export
export { variable1 as name1, variable2 asName2,... , nameN };// Deconstruct export and rename
export const { name1, name2: bar } = o;

    // Export by default
export default expression;
export default function (...) {... }// also class, function*
export default function name1(...) {... }// also class, function*
export { name1 as default,... };// Export a collection of modules
export * from... ;// does not set the default export
export * as name1 from... ;/ / Draft ECMAScript ® 2 o21
export { name1, name2, …, nameN } from... ;export { import1 as name1, import2 asName2,... , nameN }from... ;export { default } from... ;Copy the code
// name- The name of the exported value received from the module to be imported
// member, memberN- Imports multiple members with specified names from the export module
// defaultMember- From the export module, import the default export member
// alias, aliasN- alias, renaming the specified import member
// module-name- Specifies the module to be imported. It's a file name
// as- rename import member names (" identifiers ")
// from- Imports from existing modules, script files, etc
import defaultMember from "module-name";
import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name"; // The global code in the module will be run without actually importing any values.

Copy the code
// 1.js
var a  = 1;
var b = function(){
    console.log(a);
}
var c = 3;
var d = a + c;
var obj = { a,b,c }

export {a,b};

export {c,d};

export default obj;

Copy the code
<! -- 3.html Need to start a server service due to browser limitations -->
<! DOCTYPEhtml>
<html>
<head>
    <title>ES6</title>
</head>
<body>

</body>
<script type="module">
    import {a,b} from "./1.js"; / / import export
    import m1 from "./1.js"; // Import export default without {}
    import {c} from "./1.js"; // Import export On demand
    
    console.log(a); / / 1
    console.log(b); / / ƒ () {the console. The log (a); }
    console.log(m1); // {a: 1, c: 3, b: ƒ}
    console.log(c); / / 3
</script>
</html>
Copy the code