Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda