]> git.ipfire.org Git - thirdparty/bootstrap.git/commitdiff
Simplify ScrollSpy config (#33250)
authorGeoSot <geo.sotis@gmail.com>
Tue, 6 Apr 2021 15:28:10 +0000 (18:28 +0300)
committerGitHub <noreply@github.com>
Tue, 6 Apr 2021 15:28:10 +0000 (18:28 +0300)
js/src/scrollspy.js
js/tests/unit/scrollspy.spec.js

index 3667b9a12dd0d921ea77518297eb4aafd6825ebb..4e830b530b146c3c9fe9f1af865c8ec95401699f 100644 (file)
@@ -12,7 +12,6 @@ import {
   isElement,
   typeCheckConfig
 } from './util/index'
-import Data from './dom/data'
 import EventHandler from './dom/event-handler'
 import Manipulator from './dom/manipulator'
 import SelectorEngine from './dom/selector-engine'
@@ -155,6 +154,7 @@ class ScrollSpy extends BaseComponent {
   _getConfig(config) {
     config = {
       ...Default,
+      ...Manipulator.getDataAttributes(this._element),
       ...(typeof config === 'object' && config ? config : {})
     }
 
@@ -278,20 +278,17 @@ class ScrollSpy extends BaseComponent {
 
   static jQueryInterface(config) {
     return this.each(function () {
-      let data = Data.get(this, DATA_KEY)
-      const _config = typeof config === 'object' && config
+      const data = ScrollSpy.getInstance(this) || new ScrollSpy(this, typeof config === 'object' ? config : {})
 
-      if (!data) {
-        data = new ScrollSpy(this, _config)
+      if (typeof config !== 'string') {
+        return
       }
 
-      if (typeof config === 'string') {
-        if (typeof data[config] === 'undefined') {
-          throw new TypeError(`No method named "${config}"`)
-        }
-
-        data[config]()
+      if (typeof data[config] === 'undefined') {
+        throw new TypeError(`No method named "${config}"`)
       }
+
+      data[config]()
     })
   }
 }
@@ -304,7 +301,7 @@ class ScrollSpy extends BaseComponent {
 
 EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
   SelectorEngine.find(SELECTOR_DATA_SPY)
-    .forEach(spy => new ScrollSpy(spy, Manipulator.getDataAttributes(spy)))
+    .forEach(spy => new ScrollSpy(spy))
 })
 
 /**
index f7258ba355b8cc60cccb59093fa26aa16ae0417b..c4130a1aa707b8a3f527de314efa686d74ef38f8 100644 (file)
@@ -605,6 +605,23 @@ describe('ScrollSpy', () => {
       expect(ScrollSpy.getInstance(div)).toBeDefined()
     })
 
+    it('should create a scrollspy with given config', () => {
+      fixtureEl.innerHTML = '<div></div>'
+
+      const div = fixtureEl.querySelector('div')
+
+      jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface
+      jQueryMock.elements = [div]
+
+      jQueryMock.fn.scrollspy.call(jQueryMock, { offset: 15 })
+      spyOn(ScrollSpy.prototype, 'constructor')
+      expect(ScrollSpy.prototype.constructor).not.toHaveBeenCalledWith(div, { offset: 15 })
+
+      const scrollspy = ScrollSpy.getInstance(div)
+      expect(scrollspy).toBeDefined()
+      expect(scrollspy._config.offset).toBe(15)
+    })
+
     it('should not re create a scrollspy', () => {
       fixtureEl.innerHTML = '<div></div>'