From 428043f9a49bf602ee53cc5cd4e248b4e42d3f9c Mon Sep 17 00:00:00 2001 From: SleepWalker Date: Sun, 1 May 2016 10:18:34 +0300 Subject: [PATCH] Decompose Form logic from BaseAuthBody into a separate model --- src/components/auth/BaseAuthBody.jsx | 23 ++++------------- src/models/Form.js | 38 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 18 deletions(-) create mode 100644 src/models/Form.js diff --git a/src/components/auth/BaseAuthBody.jsx b/src/components/auth/BaseAuthBody.jsx index 699739a..a3f834d 100644 --- a/src/components/auth/BaseAuthBody.jsx +++ b/src/components/auth/BaseAuthBody.jsx @@ -5,6 +5,7 @@ import React, { Component, PropTypes } from 'react'; import AuthError from 'components/auth/authError/AuthError'; import { userShape } from 'components/user/User'; +import Form from 'models/Form'; export default class BaseAuthBody extends Component { static contextTypes = { @@ -31,28 +32,14 @@ export default class BaseAuthBody extends Component { onClearErrors = this.context.clearErrors; - form = {}; + form = new Form(); - bindField(name) { - return { - name, - ref: (el) => { - this.form[name] = el; - } - }; - } + bindField = this.form.bindField.bind(this.form); + serialize = this.form.serialize.bind(this.form); autoFocus() { const fieldId = this.autoFocusField; - fieldId && this.form[fieldId] && this.form[fieldId].focus(); - } - - serialize() { - return Object.keys(this.form).reduce((acc, key) => { - acc[key] = this.form[key].getValue(); - - return acc; - }, {}); + fieldId && this.form.focus(fieldId); } } diff --git a/src/models/Form.js b/src/models/Form.js new file mode 100644 index 0000000..0f1d240 --- /dev/null +++ b/src/models/Form.js @@ -0,0 +1,38 @@ +export default class Form { + fields = {}; + + /** + * Connects form with React's component + * + * Usage: + * + * + * @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; + }, {}); + } +}