mirror of
https://github.com/elyby/accounts-frontend.git
synced 2024-11-16 05:03:02 +05:30
Decompose Form logic from BaseAuthBody into a separate model
This commit is contained in:
parent
a8af63b46c
commit
428043f9a4
@ -5,6 +5,7 @@ import React, { Component, PropTypes } from 'react';
|
|||||||
|
|
||||||
import AuthError from 'components/auth/authError/AuthError';
|
import AuthError from 'components/auth/authError/AuthError';
|
||||||
import { userShape } from 'components/user/User';
|
import { userShape } from 'components/user/User';
|
||||||
|
import Form from 'models/Form';
|
||||||
|
|
||||||
export default class BaseAuthBody extends Component {
|
export default class BaseAuthBody extends Component {
|
||||||
static contextTypes = {
|
static contextTypes = {
|
||||||
@ -31,28 +32,14 @@ export default class BaseAuthBody extends Component {
|
|||||||
|
|
||||||
onClearErrors = this.context.clearErrors;
|
onClearErrors = this.context.clearErrors;
|
||||||
|
|
||||||
form = {};
|
form = new Form();
|
||||||
|
|
||||||
bindField(name) {
|
bindField = this.form.bindField.bind(this.form);
|
||||||
return {
|
serialize = this.form.serialize.bind(this.form);
|
||||||
name,
|
|
||||||
ref: (el) => {
|
|
||||||
this.form[name] = el;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
autoFocus() {
|
autoFocus() {
|
||||||
const fieldId = this.autoFocusField;
|
const fieldId = this.autoFocusField;
|
||||||
|
|
||||||
fieldId && this.form[fieldId] && this.form[fieldId].focus();
|
fieldId && this.form.focus(fieldId);
|
||||||
}
|
|
||||||
|
|
||||||
serialize() {
|
|
||||||
return Object.keys(this.form).reduce((acc, key) => {
|
|
||||||
acc[key] = this.form[key].getValue();
|
|
||||||
|
|
||||||
return acc;
|
|
||||||
}, {});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
38
src/models/Form.js
Normal file
38
src/models/Form.js
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
export default class Form {
|
||||||
|
fields = {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connects form with React's component
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* <input {...this.form.bindField('foo')} type="text" />
|
||||||
|
*
|
||||||
|
* @param {string} name - the name of field
|
||||||
|
*
|
||||||
|
* @return {Object} ref and name props for component
|
||||||
|
*/
|
||||||
|
bindField(name) {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
ref: (el) => {
|
||||||
|
this.fields[name] = el;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
focus(fieldId) {
|
||||||
|
if (!this.fields[fieldId]) {
|
||||||
|
throw new Error(`The field with an id ${fieldId} does not exists`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.fields[fieldId].focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
serialize() {
|
||||||
|
return Object.keys(this.fields).reduce((acc, key) => {
|
||||||
|
acc[key] = this.fields[key].getValue();
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user