Skip to content

Commit 1942f18

Browse files
committed
Handle dirty lazy dbModel fields.
1 parent f6bb278 commit 1942f18

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

django_unicorn/static/js/component.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,12 @@ export class Component {
148148
if (!this.attachedDbEvents.some((e) => e.isSame(element))) {
149149
this.attachedDbEvents.push(element);
150150
addDbEventListener(this, element);
151+
152+
// If a field is lazy, also add an event listener for input for dirty states
153+
if (element.field.isLazy) {
154+
// This input event for isLazy will be stopped after dirty is checked when the event fires
155+
addDbEventListener(this, element, "input");
156+
}
151157
}
152158

153159
if (!this.dbEls.some((e) => e.isSame(element))) {
@@ -162,7 +168,7 @@ export class Component {
162168
this.attachedModelEvents.push(element);
163169
addModelEventListener(this, element);
164170

165-
// If an element is lazy, also add an event listener for input for dirty states
171+
// If a model is lazy, also add an event listener for input for dirty states
166172
if (element.model.isLazy) {
167173
// This input event for isLazy will be stopped after dirty is checked when the event fires
168174
addModelEventListener(this, element, "input");

django_unicorn/static/js/eventListeners.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,12 @@ export function addDbEventListener(component, element, eventType) {
360360
}
361361
}
362362

363+
// Lazy models fire an input and blur so that the dirty check above works as expected.
364+
// This will prevent the input event from doing anything.
365+
if (element.field.isLazy && eventType === "input") {
366+
return;
367+
}
368+
363369
if (!component.lastTriggeringElements.some((e) => e.isSame(element))) {
364370
component.lastTriggeringElements.push(element);
365371
}

example/unicorn/templates/unicorn/models.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ <h3>Last 2 added flavors</h3>
6868
<h4>PK: {{ flavor.pk }}</h4>
6969
<div>
7070
<label>Name</label>
71-
<input type="text" unicorn:field.defer="name" u:dirty.class="dirty"></input>
71+
<input type="text" unicorn:field.lazy="name" u:dirty.class="dirty"></input>
7272

7373
<strong>Name</strong> {{ flavor.name }}
7474
</div>

0 commit comments

Comments
 (0)