Access IIFE function in global scope

Asked

Viewed 26 times

0

Guys, I’m doing some Javascript tests, and I need to access an IIFE function in the global scope, because the element is being created inside it and it does an execution onclick calling a function, but this function is within the IIFE scope.

(function(){

function addEle(){
    var a = document.createElement('a');
    a.setAttribute('href', '#');
    a.setAttribute('onclick', 'deleteEle(1)');
    a.appendChild(document.createTextNode('Elemento qualquer'));
    document.body.appendChild();
}

function deleteEle(pos){
    //do....
}

})();

When the user clicks on the button is called the function:

deleteEle()

that is in the local scope and Javascript does not recognize.

1 answer

1

As far as I know, functions within local scope are inaccessible from the outside. In view of this, what you could do is create a addEventListener to the element instead of a onclick:

Behold:

(function(){

   addEle(); // chama a função que irá criar o elemento
   function addEle(){
       var a = document.createElement('a');
       a.setAttribute('href', '#');
   //    a.setAttribute('onclick', 'deleteEle(1)');
       a.appendChild(document.createTextNode('Elemento qualquer'));
       document.body.appendChild(a);
       a.addEventListener("click", function(){ deleteEle(1) });
   }

   function deleteEle(pos){
       //do....
       console.log(pos);
   }

})();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.