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

129
Visualizações
maintain class scope within jquery extend function

I'm working with a ListBox class in Javascript and extended a jQuery function to handle swapping items within the list.

Everything works as expected when only one instance of ListBox exists. However, as soon as more list boxes are added, the jQuery extension seems to lose scope on a class variable.

Basically, the DOM works as expected (items are visually swapping), but the jQuery function seems to have lost the scope of the class' underlying Array. It only updates the array of the last instance of ListBox

In the example from the jsFiddle link, the 2nd ListBox items and the array are synched appropriately until an item is swapped in the 1st box, then everything starts getting lost. Also note the array of the first instance never changes.

I am able to get it working by using 'this' when declaring arItems, but 'this' is not acceptable because I don't want to expose the internal array. I considered using a class function this.getList(), but I don't believe we can make read-only properties in javascript?

The thing that stumps me the most is the jQuery elements seem to know the scope very well.. meaning that swapping in the 1st box, does not move the items in the 2nd box.. and does not enable/disable the swap buttons of the 2nd box. Only the array has seemed to lose scope and it is defined with 'let' - just the same as the jQuery elements.

const ListBox = function(){
  let $lbContainer = $('<div id="lb-container"></div');
  let $lb = $('<div id="lb-col1" class="list-group"></div>');
  let arItems = [1,2,3,4];
  ...
  ...
  // jQuery extension
  $.fn.lbMove = function(bUp){
    let $item = (bUp ? this.prev() : this.next());
    
    // swap array items
    arItems[this.index()] = arItems.splice($item.index(), 1, arItems[this.index()])[0];
    
    // swap list items
    if(bUp)
        $item.before(this)
    else
        $item.after(this)
    // button enablement
    this.click();
  }
}

https://jsfiddle.net/kL2b37h6/2/

about 4 years ago · Juan Pablo Isaza
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