Dear folks who are building and using stimulus,
I am currently working on a controller to use the PhotoSwipe lightbox library. Photoswipe differentiates between different galleries on the same page by a unique ID. For this, I would like each instance of the photoswipe-controller to have some unique ID (e.g. in a data attribute).
Currently, the only way I can think of is kind of pedestrian, something like:
document.querySelectorAll('[data-controller*="photoswipe"]').forEach((element, index) => {
element.dataset.controllerId = index
})
Can you think of a better way to identify the individual instances of the controller?
Thank you for building this awesome piece of software. It's kind of the JS framework I've been waiting for 馃槉
I think if you will use PhotoSwipe inside controller than you will have a right instance to operate with.
Yes, you're right. PhotoSwipe itself doesn't necessarily need it. I wasn't specific enough with its usage: The ID is used to identify the gallery via a GET variable in the URL, so that you can link to a specific photo in a gallery.
It's a bonus feature, and not necessary to PhotoSwipe itself, but I'm trying to implement it with stimulus.
Maybe your controller could set an auto-incrementing ID?
// photoswipe_controller.js
import { Controller } from "stimulus"
let id = 0
export default class extends Controller {
initialize() {
this.data.set("id", id++) // Sets data-photoswipe-id="[id]" on the element
}
}
Thanks, that's a much better solution!
Most helpful comment
Maybe your controller could set an auto-incrementing ID?