Skip to content

Commit f9ca65a

Browse files
committed
feat(core basepattern): Add a destroy method.
The destroy method removes the pattern instance from the element. This is necessary to re-initialize the same pattern on the same element.
1 parent ce962d2 commit f9ca65a

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

src/core/basepattern.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*/
99
import logging from "./logging";
1010

11-
const log = logging.getLogger("Patternslib Base");
11+
const log = logging.getLogger("basepattern");
1212

1313
class BasePattern {
1414
static name; // name of pattern used in Registry.
@@ -84,6 +84,13 @@ class BasePattern {
8484
once: true,
8585
});
8686
}
87+
88+
/**
89+
* Destroy/remove/unload the pattern from the element.
90+
*/
91+
destroy() {
92+
delete this.el[`pattern-${this.name}`];
93+
}
8794
}
8895

8996
export default BasePattern;

src/core/basepattern.test.js

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ describe("Basepattern class tests", function () {
117117
expect(pat3 instanceof Pat2).toBeTruthy();
118118
});
119119

120-
it("4 - The pattern instance is stored on the element itself.", async function () {
120+
it("4.1 - The pattern instance is stored on the element itself.", async function () {
121121
class Pat extends BasePattern {
122122
static name = "example";
123123
}
@@ -129,6 +129,44 @@ describe("Basepattern class tests", function () {
129129
expect(el["pattern-example"]).toBe(pat);
130130
});
131131

132+
it("4.2 - The same pattern cannot be instantiated on the same element twice.", async function () {
133+
class Pat extends BasePattern {
134+
static name = "example";
135+
}
136+
137+
const el = document.createElement("div");
138+
const pat = new Pat(el);
139+
await utils.timeout(1);
140+
141+
expect(el["pattern-example"]).toBe(pat);
142+
143+
const pat2 = new Pat(el);
144+
await utils.timeout(1);
145+
146+
expect(el["pattern-example"]).toBe(pat);
147+
expect(el["pattern-example"]).not.toBe(pat2);
148+
});
149+
150+
it("4.3 - The same pattern can be instantiated on the same element again, after the first was destroyed.", async function () {
151+
class Pat extends BasePattern {
152+
static name = "example";
153+
}
154+
155+
const el = document.createElement("div");
156+
const pat = new Pat(el);
157+
await utils.timeout(1);
158+
159+
expect(el["pattern-example"]).toBe(pat);
160+
161+
pat.destroy();
162+
163+
const pat2 = new Pat(el);
164+
await utils.timeout(1);
165+
166+
expect(el["pattern-example"]).not.toBe(pat);
167+
expect(el["pattern-example"]).toBe(pat2);
168+
});
169+
132170
it("5 - Registers with the registry.", async function () {
133171
class Pat extends BasePattern {
134172
static name = "example";

0 commit comments

Comments
 (0)