跳到正文
cccskills
免费在 GitHub 公开

frontend-patterns

Frontend JavaScript patterns for event handling, form UX, and validation integration

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md7.4 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Applicable to: Web layer JavaScript (site.js, page-specific scripts)
Last Updated: 2026-04-11
Maintainer: Sparks (Frontend Developer)

Event Handler Best Practices

Always Prevent Default Explicitly

When writing event listeners that conditionally block browser default behavior, always accept the event parameter and call preventDefault() before early returns.

❌ WRONG:

form.addEventListener('submit', function () {
    if (someCondition) return;  // ⚠️ Form still submits!
    // ... handler logic
});

✅ CORRECT:

form.addEventListener('submit', function (event) {
    if (someCondition) {
        event.preventDefault();  // ✅ Form submission blocked
        return;
    }
    // ... handler logic
});

Why It Matters

  • Early returns without preventDefault() don't stop the browser's default action
  • This causes issues like:
    • Double-submits on forms (Issue #708)
    • Unintended navigation when clicking disabled links
    • Form submission when validation fails client-side

Common Event Types Requiring preventDefault()

  1. Form Submit - Block duplicate submissions or invalid forms
  2. Link Click - Prevent navigation for disabled/loading states
  3. Keypress - Block Enter key in certain inputs
  4. Drag/Drop - Override browser default file handling

Pattern in site.js (Global Form Handler)

The project's global form submit handler (site.js) implements double-submit prevention. IMPORTANT: Use button click event, NOT form submit event, to prevent race conditions.

❌ WRONG - Race Condition:

form.addEventListener('submit', function (event) {
    if (btn.disabled) {
        event.preventDefault();
        return;
    }
    btn.disabled = true;  // ⚠️ Too late! Second click already queued submit event
});

✅ CORRECT - Click Event:

btn.addEventListener('click', function (event) {
    if (btn.disabled) {
        event.preventDefault();  // Block if already disabled
        return;
    }
    
    // Check client validation BEFORE disabling
    if (typeof $ !== 'undefined' && $(form).valid && !$(form).valid()) {
        return;  // Let validation run, don't disable
    }
    
    btn.disabled = true;  // Disable immediately on first click
    btn.innerHTML = '<span>...</span>Saving...';  // Visual feedback
});

Why Click Event Prevents Race:

  • Click event fires BEFORE form submit event
  • Button disables on FIRST click, preventing second click from queuing another submit
  • Validation check runs before disable, so invalid forms don't stay disabled

Key Points:

  • Use button click event, not form submit event
  • Check client validation BEFORE disabling button
  • Disable happens atomically on first click (no race window)
  • Re-enables button on validation errors (invalid-form.validate event)

Form UX Patterns

Submit Button States

  1. Default State: Enabled, shows action text (e.g., "Save", "Add Platform")
  2. Submitting State: Disabled, shows spinner + "Saving..."
  3. Validation Error State: Re-enabled via jQuery Validate's invalid-form.validate event

Visual Feedback

Use Bootstrap spinner for loading states:

btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Saving...';

Preserving Original Content

Store original button HTML to restore on error:

btn.dataset.originalHtml = btn.innerHTML;  // Save before change
// ... later, on error:
btn.innerHTML = btn.dataset.originalHtml;  // Restore
delete btn.dataset.originalHtml;

Integration with jQuery Validation

The project uses jQuery Unobtrusive Validation. Listen for validation failures to reset button state:

$(form).on('invalid-form.validate', function () {
    // Restore button if it was disabled for submit
    if (btn.dataset.originalHtml) {
        btn.innerHTML = btn.dataset.originalHtml;
        delete btn.dataset.originalHtml;
        btn.disabled = false;
    }
});

References

  • Issue #708: Double-submit race condition fix (click event vs submit event)
  • File: JosephGuadagno.Broadcasting.Web/wwwroot/js/site.js
  • Decision: .squad/decisions/inbox/switch-real-fix-708.md (2026-04-13)
  • Pattern: Button click event for double-submit prevention (atomic disable before form submit fires)

Razor Forms and Model Binding

Route Parameters Required for Controller Action Matching

When a controller POST action has simple-type parameters (int, string, guid) that are NOT properties of the ViewModel, those parameters MUST be included in the route. Without them, ASP.NET Core routing cannot match the action, causing HTTP 400 Bad Request.

❌ WRONG:

@model EngagementSocialMediaPlatformViewModel

<!-- Missing route parameter - causes 400 error! -->
<form asp-action="AddPlatform" method="post">
    <input type="hidden" asp-for="EngagementId" />
    <!-- ... -->
</form>

Controller:

[HttpPost]
public async Task<IActionResult> AddPlatform(int engagementId, EngagementSocialMediaPlatformViewModel vm)
{
    // ⚠️ Form POSTs to /Engagements/AddPlatform (no engagementId in route)
    // ⚠️ ASP.NET Core expects route like /Engagements/AddPlatform/5
    // ⚠️ Route doesn't match → HTTP 400
}

✅ CORRECT:

@model EngagementSocialMediaPlatformViewModel

<!-- Route parameter required for action matching -->
<form asp-action="AddPlatform" asp-route-engagementId="@Model.EngagementId" method="post">
    <input type="hidden" asp-for="EngagementId" />
    <!-- ... -->
</form>

Controller:

[HttpPost]
public async Task<IActionResult> AddPlatform(int engagementId, EngagementSocialMediaPlatformViewModel vm)
{
    // ✅ Form POSTs to /Engagements/AddPlatform/5
    // ✅ Route matches action signature
    // ✅ engagementId = 5 (from route), vm.EngagementId = 5 (from POST body)
}

Route vs. Model Binding: Different Purposes

Having BOTH asp-route-X and a matching ViewModel property is NOT a conflict:

  • Route parameter: Used by ASP.NET Core routing to match the controller action
  • Model property: Used by controller logic to access the value from the ViewModel
  • Both mechanisms are independent and don't interfere with each other

When to Use Route Parameters vs Model Properties

Use route parameters (asp-route-*) when:

  • Controller action signature has simple-type parameters (int, string) that are not ViewModel properties
  • The parameter is required for route matching
  • Example: Action(int id, ViewModelType model)

Use model properties (hidden fields) when:

  • The value is part of the ViewModel and used in controller logic
  • The value must be validated with other form fields
  • Example: vm.EngagementId used to verify data integrity

Use BOTH when:

  • The controller action signature is Action(int routeParam, ViewModelType vm) where vm has a property matching routeParam
  • The route parameter satisfies routing requirements
  • The model property satisfies business logic requirements

Related Issues

  • Issue #708: AddPlatform form returned 400 when route parameter was removed
  • Decision: .squad/decisions/inbox/sparks-708-route-parameter-correction.md (SUPERSEDES previous incorrect decision)
  • File: JosephGuadagno.Broadcasting.Web/Views/Engagements/AddPlatform.cshtml

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Standard collaboration patterns for all squad agents — worktree awareness, decisions, cross-agent communication

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Shared hard rules enforced across all squad agents

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Comprehensive AI prompt engineering safety review and improvement prompt. Analyzes prompts for safety, bias, security vulnerabilities, and effectiveness while providing detailed improvement recommendations with extensive frameworks, testing methodologies, and educational content.

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Migrate API controller scope checks to framework-enforced authorization policies while preserving ownership checks.

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Review API DTO implementations for contract/domain separation, mapping patterns, and REST compliance

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Register shared claims transformation and hierarchical role policies in the API without breaking existing scope enforcement.

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

查看 jguadagno 的全部技能

报告此技能的问题