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();
}
}