Skip to content

Commit

Permalink
Add debounce time on event listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
notthatjen committed Jun 15, 2024
1 parent b264c14 commit 7b00afb
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
31 changes: 30 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1032,7 +1032,7 @@ <h3 class="font-bold font-mono">On Change Example:</h3>
<script>
showSelect = false
</script>
<div class="p-4 border border-dashed border-black rounded mt-2">
<div class="p-4 border border-dashed border-black rounded mt-2" :clickout="showSelect = false">
<div class="flex items-end">
<div class="flex flex-col w-full">
<p class="font-bold font-mono text-sm">Custom Select:</p>
Expand Down Expand Up @@ -1107,6 +1107,35 @@ <h3 class="font-bold font-mono">On Change Example:</h3>
</svg>
</span>
</li>
<li
:click="selectedOption = 'Dwight Schrute'"
:class="selectedOption == 'Dwight Schrute' ? 'bg-indigo-600 text-white' : 'text-gray-900' "
class="text-gray-900 relative cursor-default select-none py-2 pl-3 pr-9"
id="listbox-option-0"
role="option"
>
<span
:class="selectedOption == 'Dwight Schrute' ? 'font-semibold' : 'font-normal' "
class="block truncate"
>Dwight Schrute</span
>
<span
class="text-white absolute inset-y-0 right-0 flex items-center pr-4"
>
<svg
class="h-5 w-5"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
clip-rule="evenodd"
/>
</svg>
</span>
</li>
<li
:click="selectedOption = 'Jen Villaganas'"
:class="selectedOption == 'Jen Villaganas' ? 'bg-indigo-600 text-white' : 'text-gray-900' "
Expand Down
22 changes: 15 additions & 7 deletions lib/entity/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,16 +149,24 @@ export class Events {
const listener = this.listener[attr]
if (!listener) return

if (Array.isArray(listener)) {
listener.forEach(({ el, eventName, event }) => {
el.addEventListener(eventName, event)
[].concat(listener).forEach(({ el, eventName, event }) => {
el.addEventListener(eventName, (e) => {
this.debounce(() => {
event(e)
}, 50)
})
} else {
const { el, eventName, event } = listener
el.addEventListener(eventName, event)
}
})
}

debounce(callback, wait) {
if (this.timeout) return
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
callback()
this.timeout = null
}, wait)
}

setChangeEvent() {
const el = this.entity.element
const key = ':change'
Expand Down

0 comments on commit 7b00afb

Please sign in to comment.