| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import { AnyJson, AnyStore } from '~/types/interfaces'
- import {computed, ComputedRef, useContext} from "@nuxtjs/composition-api";
- /**
- * @category composables/form
- * @class UseDirtyForm
- * Use Classe pour gérer l'apparition de message si le formulaire est dirty
- */
- export class UseForm {
- private store: AnyStore
- private readonly handler: any
- constructor () {
- const {store} = useContext()
- this.store = store
- this.handler = getEventHandler()
- }
- /**
- * Composition function
- */
- public invoke (): AnyJson {
- const readonly: ComputedRef<boolean> = computed(() => {
- return this.store.state.form.readonly
- })
- return {
- markFormAsDirty: () => this.markAsDirty(),
- markFormAsNotDirty: () => this.markAsNotDirty(),
- readonly
- }
- }
- /**
- * définit le formulaire comme Dirty (modifié)
- */
- private markAsDirty () {
- this.store.commit('form/setDirty', true)
- this.addEventListener()
- }
- /**
- * Définit le formulaire comme non dirty (non modifié)
- */
- private markAsNotDirty () {
- this.store.commit('form/setDirty', false)
- this.clearEventListener()
- }
- /**
- * Ajoute un Event avant le départ de la page
- */
- private addEventListener () {
- if (process.browser) {
- window.addEventListener('beforeunload', this.handler)
- }
- }
- /**
- * Supprime l'Event avant le départ de la page
- */
- private clearEventListener () {
- if (process.browser) {
- window.removeEventListener('beforeunload', this.handler)
- }
- }
- }
- function getEventHandler () {
- return function (e: any) {
- // Cancel the event
- e.preventDefault()
- // Chrome requires returnValue to be set
- e.returnValue = ''
- }
- }
- export const $useForm = () => new UseForm().invoke()
|