Good practice combining design patterns in JavaScript

I am currently working on my private project (for training), which is a simple to-do list. I am trying to use a modular template (to show a specific module template). The image below shows the general idea of ​​how I am going to build it.

Image of what my application looks like

Thus, each module will be in a separate js file, where each module looks like this:

var TaskModule = (function () { 

  function someFunction(parameter) {
    tasks = newTasks;
  }

}

And the question is: what if we want to create something like a separate file, let's say the 'helpers function'. It is not convenient to write in each module something like:

var someElement = document.getElementById('id')

I have a helper function (this function is just an example):

var someElement = byId('id');

, HelpersModule , , :

var someElement = HelpersModule.byId('id');

, , document.getElementById. , "HelpersModule" , , HelpersModule :

(function(window) {

    window.byId = function (selector, scope) {
      return (scope || document).getElementById(selector);
    };

})(window);

, HelpersModule . - ?

+4
2

(, HelpersModule):

const HelpersModule = {
  byId: id => document.getElementById(id),
  byTag: tag => Array.from(document.getElementsByTagName(tag))
};

... - , :

// ...
const byId = HelpersModule.byId; // if you only need 'byId'
const element = byId('my-id');
// ...

, :

const { byId } = HelpersModule; // if you only need 'byId'
const element = byId('my-id');

const { byId, byTag } = HelpersModule; // if you need both
const element = byId('my-id');
const allSpans = byTag('span');
+2

var someElement = document.getElementById('id')

var someElement = HelpersModule.byId('id');

, . , , . . / ?

Edit:

, . , , . , . , , , . , , . , , .

, (, ), . , .

0

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


All Articles