I've created a simple javascript class to wrap slick carousel.
What is the best way to instantiate multiple instances of this class?
I've currently got the below, which search the DOM and creates a new class instance of the component, if found. I suspect my project will grow a little and this 'root' file may because a little bloated/confusing. Is there a better way to organize it?
I'm going to be adding additional classes for further functionality, so trying to find the best approach early.
main.js
import Carousel from '../app/assets/javascripts/carousel/Carousel';
var carouselElements = Array.from(document.getElementsByClassName('slick-media'));
if (carouselElements) {
carouselElements.map(function (element) {
new Carousel(element, true, {xs: 6, md: 6, lg: 6 });
});
}
Carousel.js
export default class Carousel {
constructor(element, variableWidth = false, breakpoint) {
this.element = element;
this.variableWidth = variableWidth;
this.breakpoint = breakpoint
this._init(element);
/* Bind methods */
this._init = this._init.bind(this);
}
_init() {
this._instantiateSlick(this.element);
}
_instantiateSlick(element) {
$(element).slick({
lazyLoad: 'ondemand',
slidesToScroll: 1,
adaptiveHeight: true,
useTransform: true,
/* Default over lg breakpoint */
slidesToShow: this.breakpoint.lg,
/* Allow slick to calculate widths */
variableWidth: this.variableWidth,
responsive: [
{
breakpoint: 1199,
settings: {
slidesToShow: this.breakpoint.lg,
slidesToScroll: 1,
infinite: true
}
},
{
breakpoint: 991,
settings: {
slidesToShow: this.breakpoint.md,
slidesToScroll: 1,
infinite: true
}
},
{
breakpoint: 480,
settings: {
slidesToShow: this.breakpoint.xs,
slidesToScroll: 1,
infinite: true
}
}]
});
}
}