본문으로 건너뛰기
cccskills
무료GitHub에 공개

frontend-patterns

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

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md7.4 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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 / 1,000자

이 양식은 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의 스킬 모두 보기

이 스킬의 문제 신고