@smnandre/stimulus-listeners
Version:
A Stimulus plugin for declarative DOM event listeners via static `listeners` or explicit API.
41 lines (40 loc) • 1.32 kB
JavaScript
function f(e, t) {
if (!t) return e.element;
if (typeof t == "string") {
const s = e.element.querySelector(t);
if (!s) throw new Error(`No element matches selector "${t}"`);
return s;
}
return t;
}
function a(e, t) {
var c, u;
const s = (c = e.connect) == null ? void 0 : c.bind(e), o = (u = e.disconnect) == null ? void 0 : u.bind(e);
e.connect = function() {
s == null || s(), this._managedListeners = [], Object.entries(t).forEach(([d, n]) => {
let h, i, r;
typeof n == "string" ? (h = n, i = void 0, r = this.element) : Array.isArray(n) ? ([h, i] = n, r = this.element) : (h = n.method, i = n.options, r = f(this, n.target));
const m = this[h].bind(this);
r.addEventListener(d, m, i), this._managedListeners.push({ eventName: d, handler: m, options: i, target: r });
});
}, e.disconnect = function() {
var d;
(d = this._managedListeners) == null || d.forEach(
({ eventName: n, handler: h, options: i, target: r }) => {
r.removeEventListener(n, h, i);
}
), this._managedListeners = [], o == null || o();
};
}
function L(e) {
const s = e.constructor.listeners;
s && a(e, s);
}
function p(e, t) {
a(e, t);
}
export {
p as useEventListeners,
L as useListeners
};
//# sourceMappingURL=stimulus-listeners.es.js.map