Richard
Richard

Reputation: 509

How to call a Javascript Function which is nested inside a forEach loop

I'm trying to modify a plugin for adding input tags which is available here

I've written a dumbed down version of my issue below. The pluggin searches the page for any HTML with the class 'tags-input' and creates a bunch of functions for each one found to add and remove tags. The pluggin triggers the addTag() function whenever a keydown event is detected.

[].forEach.call(document.getElementsByClassName('tags-input'), function (el) {
  function addTag(str){
    //code here adds a tag with a certain string "str"
  }
});

addTag("some string"); //function not found!

I want to be able to call the addTag() function from outside the forEach loop when a link from a live search is selected.

I've tried adding listeners within the loop, however, since the links from the live search are generated from a database after the page loads the listeners don't appear to pick them up.

How can I call the addTag() function from my live search?

Similar questions did not help with this specific issue:

Call javascript inside foreach loop - No Answer Given

call javascript function outside foreach loop - Different issue as far as I can tell

Upvotes: 0

Views: 190

Answers (1)

Mosia Thabo
Mosia Thabo

Reputation: 4267

Something Like This, No?

I understand what you're trying to do: But to make this simple I've used a List of String Values just to represent another possible approach:

//  Why not create a list of functions which correspond to each list item?
var doSomeThingFuncList = [];

["Yes","No","Maybe"].forEach(function (item) {
  // Assuming that we will create a function for each list item that must be called outside of the loop
  doSomeThingFuncList.push(
    () => {
      alert("Do Something");
    }
  );
});
// The functions we have defined inside the for-loop can now be called from outside the forEach loop through indexing the function list defined at the beginning

doSomeThingFuncList[0]();

Basically, knowing what function to run what index of the array you'd be able to callback these functions through events on those buttons. But I am not sure what the scenario is behind this.

Upvotes: 2

Related Questions