D
D
Dubrovin2018-02-05 10:04:19
JavaScript
Dubrovin, 2018-02-05 10:04:19

How to format helper functions correctly?

Hello,
I want to create my own helper functions, something like:

/* helpers.js */
function find( el, selector ) {
    return el.querySelector( selector );
}

function on( el, event, callback ) {
    el.addEventListener( event, callback );
}

in order to shorten the code.
The functions themselves will be described in the helpers.js file, which will be placed by the RollupJS collector at the beginning of the final JS file (ES6 import / export is used, but import / export is not included in the final file).
It is not clear how best to organize the storage of these functions. If left as is, they will end up in window (there may be conflicts), if put in a global variable, for example, abc like this:
/* helpers.js */
abc.find = function( el, selector ) {
    return el.querySelector( selector );
}

abc.on = function( el, event, callback ) {
    el.addEventListener( event, callback );
}

then when calling, you will have to write abc each time, for example, abc.find( el, selector) ...
Well, I came across an article: https://frontender.info/designing-javascript-apis-...
I want to use chains of methods, to write not abc.find( el, selector ), but el.find( selector ), as is done in jQuery.
Can someone provide a code example of how this can be done? You need some kind of mini-jQuery for your needs.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-02-05
@Minifets

el.find( selector ), just like jQuery does.

You are slightly wrong. Because with jQuery, you don't work with the element directly, but wrap it with a wrapper from jQuery.
If you need to extend the functionality of native things, then this can be done like this:
String.prototype.customFunction = function () {
    console.log('кастомная функция');
};

let a = 'test';
a.customFunction();
"test".customFunction();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question