Im trying to merge multiple codes from multiple files into one. All have different js classes but all the same slick slider settings inside. I mean the part initSlider() {...}); Any idea how to merge them into one?
// Code inside File one
window.$ = window.jQuery = $ = jQuery;
class BRPScarousel{
constructor() {
this.els = $('.msbrps');
this.slidesToShow = maxbrp_data.slides_to_show;
this.initSlider();
}
initSlider() {
$('.new_products').css("visibility","visible");
this.els.not('.slick-initialized').slick({
// always the same
});
}
}
var sc = new BRPScarousel();
// Code inside File two
window.$ = window.jQuery = $ = jQuery;
class XCPScarousel{
constructor() {
this.els = $('.msxcps');
this.slidesToShow = maxcrp_data.slides_to_show;
this.initSlider();
}
initSlider() {
$('.bestr_products').css("visibility","visible");
this.els.not('.slick-initialized').slick({
// always the same
});
}
}
var sc = new XCPScarousel();
CodePudding user response:
From the comment on @Zulfe's answer...
"For the OP's use case one needs exactly a single (but of cause generic enough implemented)
ProductCarousel. At instantiation time one, in addition to the slideshow specific data object (e.g.maxbrp_dataormaxcrp_data, etc.), has to pass both root node selectors one forthis.els(e.g.'.msbrps'or'.msxcps', etc.) and another one forinitSlider(e.g.'.new_products'or'.bestr_products', etc.). Of cause there needs to be an initialization task, which e.g. at DOMContentLoaded time takes care of whatever needs to be initialized."
// e.g. file ... src/utils/ProductCarousel.js
class ProductCarousel {
constructor(data, elementsSelector, sliderSelector) {
this.els = $(elementsSelector);
this.slidesToShow = data.slides_to_show;
this.sliderSelector = sliderSelector
this.initSlider();
}
initSlider() {
$(this.sliderSelector).css("visibility", "visible");
this.els.not('.slick-initialized').slick({
// always the same
});
}
}
export default ProductCarousel;
// end of file.
// e.g. file ... src/main.js
import ProductCarousel from 'src/utils/ProductCarousel.js'
$(document).ready(() => {
const brpsCarousel =
new ProductCarousel(maxbrp_data, '.msbrps', '.new_products');
const xcpsCarousel =
new ProductCarousel(maxcrp_data, '.msxcps', '.bestr_products');
});
// end of file.
CodePudding user response:
Use inheritance for this.
class SimpleCarousel {
constructor(className, data) {
this.els = $('.' className);
this.slidesToShow = data.slides_to_show;
this.initSlider();
}
initSlider() {
$('.bestr_products').css("visibility", "visible");
this.els.not('.slick-initialized').slick({
// always the same
});
}
}
class BRPScarousel extends SimpleCarousel {
constructor() {
super('msbrps', maxbrp_data);
}
}
class XCPScarousel extends SimpleCarousel {
constructor() {
super('msxcps', maxcrp_data);
}
}
