samedi 25 avril 2020

Javascript - how to split / divide revealing module into smaller parts?

I would like to split / divide my module "Engine" into smaller parts (and keep it in one file).

Suppose I have a lot of code in a method "paintText()" - this code should be in in separate part.

How to do this?

My module "Engine" is like:

HTML

 <button type="button" id="addText">1. Add some text</button> 
 <button type="button" id="countText">2. Count letters</button> 
 <button type="button" id="addColor">3. Add color</button> 

<div id="elText"></div>
- - - - - - - - - - - - - - - - - - 
<div id="elCounter"></div>

Javascript:

var Engine = (function(){
    var addTextButton = document.querySelector('#addText');
    var countButton = document.querySelector('#countText');
    var colorButton = document.querySelector('#addColor');

    var textArea = document.querySelector('#elText');
    var counter = document.querySelector('#elCounter');

    addTextButton.addEventListener('click', addText, false);
    countButton.addEventListener('click', showCounter, false);
    colorButton.addEventListener('click', paintText, false);

    // Engine function
    function addText( event ){
        textArea.innerHTML += '<br /> add some text';
    }
    // Engine function
    function showCounter( event ){
        counter.innerHTML = 'amount of liter = ' + textArea.innerText.length;
    }

    // ADDITION function - separate it as submodule!!!
    function paintText( event ){
        /*
            lot of code....
            lot of code....
        */
        textArea.style.backgroundColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);// random color
    }

    return {
        paintText : paintText
    }
})();

It is simple - you can: 1. add some text 2. count letters 3. add background color.

Working JSFiddle - "One big Module":

I am trying to separate "paintText()" method into submodule, but I don't know how to do this right way.

Wrong way:

I created 2 modules "Engine" and "Color", it works but this is stupid to have 2 modules.

var Engine = (function(){
    (...)


    function randomColor( event ){

        Color.paintText( textArea )

    }
})();

//submodule
var Color = (function(){
    function paintText(){
    }
    return {
        paintText : paintText
    }
})();

Working JSFiddle - "Splitted Module - wrong way"

It know it should look like this (to keep all parts in one object) :

pseudo code:

app = {};

//engine
app.engine = function(){
... engine here
}

//additional submodule
app.color = function(){
... color here
}

//additional submodule
app.images = function(){
... images here
}

but I don't know how to make it work!

Help please.

Aucun commentaire:

Enregistrer un commentaire