selectize.js icon indicating copy to clipboard operation
selectize.js copied to clipboard

Can't add items to a (multi) select after updating inputs (in order)

Open cpsievert opened this issue 1 year ago • 1 comments

This codepen demonstrates the issue. In there, clicking the button (which updates the inputs with new options) breaks the 1st input's click-to-select behavior. Here's a screencast of the issue:

selectize-bug2

It's worth noting this isn't a problem with the latest release (v0.15.2), but it is a problem with the current HEAD of the master branch (https://github.com/selectize/selectize.js/commit/e3f2e0b4aa251375bc21b5fcd8ca7d374a921f08), which is the version the codepen is above using.

Also, the codepen console.log()s some information related to (what appears to be) the source of the issue (eventNS). Here's my understanding of it.

  1. Everytime .selectize() is called, it increases a global count, and uses that count for eventNS:

https://github.com/selectize/selectize.js/blob/e3f2e0b4aa251375bc21b5fcd8ca7d374a921f08/src/selectize.js#L29

  1. In .setup() (which is called from .selectize()), that eventNS gets used to namespace events like this one:

https://github.com/selectize/selectize.js/blob/e3f2e0b4aa251375bc21b5fcd8ca7d374a921f08/src/selectize.js#L240-L240

  1. Also, the .destroy() method decrements that global count

https://github.com/selectize/selectize.js/blob/e3f2e0b4aa251375bc21b5fcd8ca7d374a921f08/src/selectize.js#L2379-L2382

As a result, if you initialize say 2 selectize inputs, the count will be at 2. If you then .destroy() the 1st widget (taking the count back to 1), then re-initialize it (bumping the count back to 2), then the the 1st widget winds up with the same eventNS as the 2nd widget.

Looking back at the history of this code gives us some insight into how this problem arose. Note that, the .destroy() method was first added by @brianreavis, and introduced the eventNS concept. In that first version, bumping the global count was fine, since the .destroy() method didn't decrement it. However, later on, a decrement was added to destroy for another, unrelated reason.

It is a bit surprising to me that this issue has been around for nearly 7 years (and doesn't seem to be an issue for this particular behavior in v0.15.2), but I've been able to confirm, at least, that using a truly unique ID for eventNS will fix this particular problem (PR incoming)

cpsievert avatar Oct 20 '23 14:10 cpsievert

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 5 days

github-actions[bot] avatar Feb 18 '24 02:02 github-actions[bot]