Skip to content

Commit

Permalink
(feat) add domutils - bindInput
Browse files Browse the repository at this point in the history
Signed-off-by: Muthu Kumar <[email protected]>
  • Loading branch information
MKRhere committed Jul 4, 2021
1 parent 0973dd9 commit 5ba3899
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 9 deletions.
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from "./src/state.ts";
export * from "./src/h_element.ts";
export * from "./src/parse.ts";
export * from "./src/render.ts";
export * from "./src/domutils.ts";
8 changes: 8 additions & 0 deletions src/domutils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { SimpleState } from "./state.ts";

export const bindInput =
<State extends SimpleState>(state: State) =>
(el: HTMLElement) =>
el.addEventListener("input", e =>
state.publish((e?.target as unknown as { value: string }).value),
);
6 changes: 4 additions & 2 deletions src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ export const STATE = Symbol("@hyperactive/state");

export type Subscriber<T> = (val: T) => void;

export type SimpleStateRO<T = unknown> = {
// deno-lint-ignore no-explicit-any
export type SimpleStateRO<T = any> = {
init: T;
subscribe: (f: Subscriber<T>) => void;
transform: <U, Mapper extends (t: T) => U>(
Expand All @@ -11,7 +12,8 @@ export type SimpleStateRO<T = unknown> = {
[STATE]: true;
};

export type SimpleState<T = unknown> = SimpleStateRO<T> & {
// deno-lint-ignore no-explicit-any
export type SimpleState<T = any> = SimpleStateRO<T> & {
publish: (next: T) => void;
readonly: () => SimpleStateRO<T>;
};
Expand Down
8 changes: 1 addition & 7 deletions test.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,9 @@ renderDOM(
{ class: "container" },
h3("Enter a number, it should double below"),
input({
ref: bindInput(state),
id: "input-el",
value: state.init,
on: {
input: e => {
state.publish(
(e.target as unknown as { value: string }).value,
);
},
},
}),
p(state.transform(v => span(String(parseFloat(v) * 2)))),
),
Expand Down

0 comments on commit 5ba3899

Please sign in to comment.