惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
H
Heimdal Security Blog
Jina AI
Jina AI
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
AWS News Blog
AWS News Blog
C
Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Hacker News
The Hacker News
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
S
Securelist
P
Privacy International News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
博客园 - 叶小钗
J
Java Code Geeks
V
V2EX
博客园 - Franky
Spread Privacy
Spread Privacy
K
Kaspersky official blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Simon Willison's Weblog
Simon Willison's Weblog
Project Zero
Project Zero
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
C
Cybersecurity and Infrastructure Security Agency CISA
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
NISL@THU
NISL@THU
罗磊的独立博客
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园_首页
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
_action: Declarative Event Handlers in an Attribute
Jon Nyman · 2026-06-25 · via DEV Community

Introduction

In HTML Traits I went looking for a cleaner way to attach
behavior to an element than wrapping it in a custom element. Traits got me most
of the way there: composition over inheritance, multiple behaviors per element,
no wrapper soup. But once I started building real pages I noticed that the
majority of the behavior I wanted wasn't really a "component" at all. It was
just: when this changes, submit the form. Or: when this form submits, reset
it
. Reaching for a class with a constructor and a lifecycle to express "call
this function on change" felt like too much ceremony.

So I wrote something even smaller. It lives in
_action.ts
and the whole thing is about 60 lines. Instead of defining a behavior and
registering it, you name a function and bind it to an event with an attribute:

<form _change=submit method=post action="?handler=editTeam">
    ...
</form>

When anything inside that form fires a change event, the function named
submit runs. That's it. No custom element, no trait definition, no wrapper.

How it works

There is a single set of delegated listeners on the document:

for (let event of ["click", "change", "submit"]) {
  doc.addEventListener(event, e => {
    let target = e.target
    let action = findAttr(target, event)
    if (!action) return
    handleCall(e, target, action)
  })
}

That ["click", "change", "submit"] list isn't special — it's just the set
this app happens to use. The mechanism works for any bubbling event, so if
you want input, keydown, focusout, or a custom event of your own, you add
its name to the list and you immediately get a matching _input / _keydown /
_focusout attribute to bind against. Nothing else changes.

For each event type it walks up from the target with closest([_${event}])
to find the nearest _click / _change / _submit attribute, with a fallback
to the element's owning form. The attribute's value is a space-separated list
of function names that live on window.app, and each one is called with a small
context object:

fn.call(null, { app: w.app, ev: e, target, el: target, form })

Because the listener is delegated at the document, it works for elements that
were swapped in later (this app morphs HTML in from the server), and because the
value can hold several names you get composition for free:

<input name=newPlayerName required _submit="reset clearAutoFocus">

Registering a handler is just hanging a function off window.app:

Object.assign(window.app, {
  reset: ({ form }) => form?.reset(),
  clearAutoFocus: ({ target }) => target.removeAttribute("autofocus"),
})

There is also a _load attribute, handled separately, for the "run this once
when the element appears" case. It fires on page load and again on hz:completed
(after server HTML is morphed in), then removes itself so it only runs once per
element:

The hz:completed event comes from
htmz-be, a small library I wrote for
morphing server HTML into the page. It was inspired by
htmz and
Datastar. It dispatches
hz:completed after a swap, which is the hook _action uses to re-run
_load handlers on freshly inserted elements.

function handleLoad() {
  for (let el of doc.querySelectorAll("[_load]")) {
    let action = el.getAttribute("_load")
    handleCall(new Event("load"), el, action)
    el.removeAttribute("_load")
  }
}

Most of the time it's this simple

In the soccer app the overwhelming majority of interactivity is a one-liner
attribute. Auto-submit a settings form as you edit it:

<form _change=submit method=post action="?handler=editTeam&teamId=${team.id}">

Reset the "add player" form after it submits, and drop the autofocus once
you've used it:

<form _submit=reset method=post action="?handler=addPlayer">
    <input name=newPlayerName required autofocus _submit=clearAutoFocus>
</form>

None of these needed a component, a lifecycle, or a definition. The function is
named, the attribute points at it, done.

When it gets more involved: the game timer

The interesting case is the live game timer. A <span> that ticks up every
second, can flash, can be paused (static), and ticks for several elements at
once on the page. Here _action is just the entry point — the _load
attribute instantiates a real class:

<span _load="gameTimer" data-total="${total}" data-static>00:00</span>

window.app.gameTimer = ({ el }) => {
  if (el._) return   // guard against double-init
  el._ = true
  new GameTimer(el)
}

The GameTimer class then does everything a stateful component does — but
notice it has to assemble its own lifecycle out of parts:

class GameTimer {
  constructor(el) {
    this.el = el
    this.interval = +(el.dataset.interval ?? 0) || 1e3
    document.addEventListener("hz:completed", this)
    window.app.disconnectWatcher?.(el, this)   // <-- borrowed teardown
    this.update(Date.now())
  }

  disconnectedCallback() {
    timer.remove(this)
    document.removeEventListener("hz:completed", this)
  }
  // ...
}

Two things stand out compared to the simple case:

  1. "Connected" is manual. _load is the moment of construction, and the el._ guard exists because, unlike a web component, nothing stops the same element from being initialized twice.
  2. "Disconnected" is borrowed. There's no native callback when the element leaves the DOM, so the app provides a disconnectWatcher — a single MutationObserver on document.body that calls disconnectedCallback() on registered instances when their node is removed. The timer leans on that to clean up its setInterval and its event listener.

This is the honest tradeoff: _action gives you next to nothing for free, so
when you do need real component semantics you reassemble them yourself from a
load hook, a guard flag, and a shared disconnect watcher. For one timer that's
fine. If half your page were stateful widgets, you'd feel the missing
lifecycle.

Comparing the three

All three solve the same underlying problem — attach behavior to HTML without
an SPA framework
— but they sit at different points on the
simplicity-vs-encapsulation curve.

Web components

Pros:

  • Real, browser-native lifecycle: connectedCallback, disconnectedCallback, attributeChangedCallback.
  • Encapsulation, optional Shadow DOM, and a proper custom element registry.
  • Standard — no library to ship.

Cons:

  • Custom element names must contain a dash, and you generally wrap your semantic HTML in a non-semantic element.
  • Built-in/customized elements (the is= form) aren't supported in Safari, and even there you get only one behavior per element.
  • You re-learn and re-implement APIs that native elements already give you, and composing several behaviors means nesting several elements.

HTML Traits

Pros:

  • Composition: traits="elastic-textarea character-limit", multiple, ordered behaviors on one element, no wrappers.
  • Keeps the native element (and its native attributes like maxlength), so you learn less and reimplement nothing.
  • Built for progressive enhancement; mirrors the web-component class API (constructor(el), disconnectedCallback) so it's familiar.

Cons:

  • It's still "components": you define a class and register it for every behavior, which is more than some interactions deserve.
  • A library you ship, and a partial reimplementation of web components — no Shadow DOM, never a true custom element.

_action

Pros:

  • The smallest of the three (~60 lines, one set of delegated listeners). No per-element registration, no definitions — just name a function on window.app and point an attribute at it.
  • Naturally composable (_submit="reset clearAutoFocus") and form-aware (it falls back to the owning form), which is exactly what MPA-style pages need.
  • Works with server-morphed HTML out of the box because it's delegated at the document.
  • Right-sized for the common case, which is "run this function on this event," not "instantiate a stateful component."

Cons:

  • No lifecycle by default. Initialization is a manual _load hook (plus a guard flag to avoid double-init), and teardown only exists if you opt into the shared disconnectWatcher.
  • No encapsulation — every handler is a global on window.app, so naming is on you.
  • It's event handlers, not components: for genuinely stateful widgets (the game timer) you end up rebuilding the very lifecycle that traits and web components hand you.

Which one when?

I think of it as a ladder, not a competition:

  • _action for the 90% that is "on this event, call this function" — auto-submit, reset, confirm, toggle a class. It's the default reach.
  • HTML Traits when a behavior is genuinely a reusable, stateful enhancement of a native element and you want clean composition without wrappers.
  • Web components when you need true encapsulation, Shadow DOM, or you're shipping a widget for other people's pages to consume.

The pattern I keep coming back to is that most "interactivity" on a server-driven
page isn't a component at all. _action lets me stop pretending it is.


This was originally posted on jnyman.com.