Skip to content

Commit 7fc2b96

Browse files
committed
Refactor code
1 parent e8f9781 commit 7fc2b96

File tree

3 files changed

+11
-12
lines changed

3 files changed

+11
-12
lines changed

theme-switch.js

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -121,34 +121,33 @@ class ThemeSwitchElement extends HTMLElement {
121121

122122
constructor() {
123123
super();
124-
125124
// See https://stackoverflow.com/q/2305654/8583692
126125
this.shadowRoot = this.attachShadow({ mode: "open" });
127126
this.shadowRoot.innerHTML = generateIcon(...getInitialStateForIcon());
128-
129127
// Add the click listener to the top-most parent (the custom element itself)
130128
// so the padding etc. on the element be also clickable
131-
this.shadowRoot.host.addEventListener("click", () => {
132-
const oldTheme = getUserThemeSelection();
133-
this.toggleTheme(oldTheme);
134-
const newTheme = getUserThemeSelection();
135-
this.dispatchEvent(this.createEvent(oldTheme, newTheme));
136-
});
137-
129+
this.shadowRoot.host.addEventListener("click", this.onClick);
138130
// If another theme switch in page toggled, update my icon too
139131
document.addEventListener(CUSTOM_EVENT_NAME, event => {
140132
if (event.detail.originId !== this.identifier) {
141133
this.adaptToTheme();
142134
}
143135
});
144-
145136
// Create some CSS to apply to the shadow DOM
146137
// See https://css-tricks.com/styling-a-web-component/
147138
const style = document.createElement("style");
148139
style.textContent = generateStyle();
149140
this.shadowRoot.append(style);
150141
}
151142

143+
onClick() {
144+
const oldTheme = getUserThemeSelection();
145+
this.toggleTheme(oldTheme);
146+
const newTheme = getUserThemeSelection();
147+
const event = this.createEvent(oldTheme, newTheme);
148+
this.dispatchEvent(event);
149+
}
150+
152151
// See https://stackoverflow.com/a/53804106/8583692
153152
createEvent(oldTheme, newTheme) {
154153
return new CustomEvent(CUSTOM_EVENT_NAME, {

theme-switch.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)