Skip to content

Commit

Permalink
Add proxy instance creation on instantiation
Browse files Browse the repository at this point in the history
  • Loading branch information
Jerome (Thavarshan) Thayananthajothy committed Oct 8, 2023
1 parent 1160a51 commit 6e35b24
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/clients/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { hasFilesDeep } from './../support/helpers';
import { objectToFormData } from './../support/form-data';
import { ErrorRepsonse } from './../interfaces/exceptions/error-response';
import { RequestTypes } from './../interfaces/http/request-types';
import { reservedFieldNames } from '../support/field-name-validator';

export class Form implements FormInterface {
/**
Expand Down Expand Up @@ -69,6 +70,13 @@ export class Form implements FormInterface {
*/
private recentlySuccessful = false;

/**
* Indicate if the form has been modified.
*
* @var {boolean}
*/
private isDirty = false;

/**
* The default HTTP handler instance to use for form submission.
*
Expand All @@ -88,6 +96,9 @@ export class Form implements FormInterface {
data: Record<string, any> = {},
options?: FormOptions
) {
this.resetStatus();
this.isDirty = false;

this.withData(data).withOptions(options);

if (options?.http) {
Expand All @@ -97,6 +108,30 @@ export class Form implements FormInterface {
if (options?.errorHandler) {
this.setErrorHandler(options.errorHandler);
}

return this.getProxy(this);
}

/**
* Create a new form instance as a proxy.
*
* @return {Form}
*/
public getProxy (instance: Form): Form {
return new Proxy(instance, {
set: (obj: Form, prop: string, value) => {
_.set(obj, prop, value);

if (
reservedFieldNames.indexOf(prop as any) === -1 &&
value !== obj.initial[prop as string]
) {
obj.setIsDirty(true);
}

return true;
}
});
}

/**
Expand Down Expand Up @@ -672,6 +707,26 @@ export class Form implements FormInterface {
this.recentlySuccessful = state;
}

/**
* Determine if the form has been modified.
*
* @return {boolean}
*/
public getIsDirty (): boolean {
return this.isDirty;
}

/**
* Set status properties to indicate form has been modified.
*
* @param {boolean} state
*
* @return {void}
*/
public setIsDirty (state: boolean): void {
this.isDirty = state;
}

/**
* Determine if the given request type is supported.
*
Expand Down

0 comments on commit 6e35b24

Please sign in to comment.