Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
Passing in a function as an argument to another function and apply it to the passed in element

I'm trying to create some helper functions like what jQuery does but in vanilla JS.

This is what I have;

var $ = function(selector){
  var elements = typeof selector == 'string' ? document.querySelectorAll(selector) : selector;

  elements.each = function(){
    this.forEach(function(item, index){
      var element = _(this[index]);
      //How do I apply the passed in function to this element??
    })
  };
}

It is used as such;

var x = 0;
$('.field').each(function(e){
  e.addClass('item-' + x);

  x++;
});

How do I use the function I am passing in above into the $ object and apply it to the passed in element?

There are A LOT of questions asked around this but not for my specific issue, and I couldn't modify them to suit my situation. Any help is appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Although epascarello posted a way to lay out the chaining you want to accomplish, I wanna also bring up that the current way you have things set up are contradictory.

One being that you define an each() method on the elements variable you create, and two being that you define the each() method to take no parameters, but then you go on to pass a function as a parameter when you're using the method. Also the way you are referencing the elements you queried is somewhat messed up.

I think you should instead restructure your code into something like:

const $ = function(selector){
  let elements;
  
  let bundle = {
      get(selector){
        return typeof selector == 'string' ? document.querySelectorAll(selector) : selector;
      },
      each(executor) {
        // instead of calling forEach on 'this', call it on the elements instead
        // thanks to closures, this each() method still has access to the elements that were queried
        elements.forEach(function(item, index){
            let tempEle = item;
            // you can call the passed executor function here
            executor();
        });
      }
  }

  elements = bundle.get(selector);

  return bundle;
}

So you could then call it as below, where you send in an executor function to be applied each iteration thru the forEach() loop defined within each()

$('.field').each(() => {
    console.log("Calling in the each() method");
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda