From 4afc28ffcb8e6e206d76deac132602dde343ac9e Mon Sep 17 00:00:00 2001 From: Vladimir Kharlampidi Date: Fri, 22 Feb 2019 22:00:46 +0300 Subject: [PATCH] Virtual: removeSlide, removeAllSlides + tweaks for preprendSlides Fixes #2966 Ref ##2976 --- demos/410-virtual-slides.html | 10 ++++---- src/components/virtual/virtual.js | 39 +++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/demos/410-virtual-slides.html b/demos/410-virtual-slides.html index df944a1c0..c61a03c98 100644 --- a/demos/410-virtual-slides.html +++ b/demos/410-virtual-slides.html @@ -80,7 +80,7 @@ diff --git a/src/components/virtual/virtual.js b/src/components/virtual/virtual.js index c4696c770..2a95f9cff 100644 --- a/src/components/virtual/virtual.js +++ b/src/components/virtual/virtual.js @@ -133,7 +133,7 @@ const Virtual = { let newActiveIndex = activeIndex + 1; let numberOfNewSlides = 1; - if (typeof slides === 'object' && 'length' in slides) { + if (Array.isArray(slides)) { for (let i = 0; i < slides.length; i += 1) { if (slides[i]) swiper.virtual.slides.unshift(slides[i]); } @@ -146,13 +146,46 @@ const Virtual = { const cache = swiper.virtual.cache; const newCache = {}; Object.keys(cache).forEach((cachedIndex) => { - newCache[cachedIndex + numberOfNewSlides] = cache[cachedIndex]; + newCache[parseInt(cachedIndex, 10) + numberOfNewSlides] = cache[cachedIndex]; }); swiper.virtual.cache = newCache; } swiper.virtual.update(true); swiper.slideTo(newActiveIndex, 0); }, + removeSlide(slidesIndexes) { + const swiper = this; + if (typeof slidesIndexes === 'undefined' || slidesIndexes === null) return; + let activeIndex = swiper.activeIndex; + if (Array.isArray(slidesIndexes)) { + for (let i = slidesIndexes.length - 1; i >= 0; i -= 1) { + swiper.virtual.slides.splice(slidesIndexes[i], 1); + if (swiper.params.virtual.cache) { + delete swiper.virtual.cache[slidesIndexes[i]]; + } + if (slidesIndexes[i] < activeIndex) activeIndex -= 1; + activeIndex = Math.max(activeIndex, 0); + } + } else { + swiper.virtual.slides.splice(slidesIndexes, 1); + if (swiper.params.virtual.cache) { + delete swiper.virtual.cache[slidesIndexes]; + } + if (slidesIndexes < activeIndex) activeIndex -= 1; + activeIndex = Math.max(activeIndex, 0); + } + swiper.virtual.update(true); + swiper.slideTo(activeIndex, 0); + }, + removeAllSlides() { + const swiper = this; + swiper.virtual.slides = []; + if (swiper.params.virtual.cache) { + swiper.virtual.cache = {}; + } + swiper.virtual.update(true); + swiper.slideTo(0, 0); + }, }; export default { @@ -175,6 +208,8 @@ export default { update: Virtual.update.bind(swiper), appendSlide: Virtual.appendSlide.bind(swiper), prependSlide: Virtual.prependSlide.bind(swiper), + removeSlide: Virtual.removeSlide.bind(swiper), + removeAllSlides: Virtual.removeAllSlides.bind(swiper), renderSlide: Virtual.renderSlide.bind(swiper), slides: swiper.params.virtual.slides, cache: {},