Restrict JavaScript function calls to DOM element built-in event handlers

Is there any approach or workaround to create (global, if you like, but not necessarily) a function that is available only to the built-in event handlers of DOM elements?

Javascript

function forInlineCallsOnly() {
    // only callable from inline "on" attributes of DOM elements
};

That is, the above function cannot be called from other parts of the script, only from, for example:

HTML

<a onclick="forInlineCallsOnly();">Click me</a>

Is this possible using stack trace?


Note. This is not a matter of best practice as to where event handlers should be defined.

+4
source share
2 answers

The best answer I can give; and damn it is not great.

<a data-onclick-attach="forInlineCallsOnly">

Js

eventMethodsMap: {
  forInlineCallsOnly: function() {
    ...
  }
}
Array.prototype.forEach.call(document.querySelectorAll('[data-onclick-attach]'), function(elem) {
  elem.onclick = eventMethodsMap[elem.dataset.onclickAttach];
});

, , Dojo; HTML , . onclick-specific, .

EDIT: onClickAttach, , onclick.

+2

isElement : JavaScript isDOM - , JavaScript DOM?

:

HTML:

<a onclick="forInlineCallsOnly(this);">Click me</a>

JAVASCRIPT:

function forInlineCallsOnly(obj) {
    // only callable from inline "on" attributes of DOM elements
    if(!isElement(obj)){
        return;
    }
    // Put code you want to allow to run here
};
-1

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


All Articles