Stimulus: Controller ID or access to all controllers of the same type?

Created on 22 Jan 2018  路  4Comments  路  Source: hotwired/stimulus

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 馃槉

Most helpful comment

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
  }
}

All 4 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gerdriesselmann picture gerdriesselmann  路  3Comments

joeybeninghove picture joeybeninghove  路  4Comments

MrHubble picture MrHubble  路  3Comments

paulozoom picture paulozoom  路  4Comments

angarc picture angarc  路  3Comments