trc-client-core
Version:
The core of the TRC Client
102 lines (95 loc) • 3.48 kB
JavaScript
var Reflux = require('reflux');
var _ = require('lodash');
var Immutable = require('immutable');
var ImmutableStoreMixin = require('reflux-immutable/ImmutableStoreMixin');
var QandaActions = require('trc-client-core/src/qanda/QandaActions');
var QandaStore = require('trc-client-core/src/qanda/QandaStore');
var QandaEditQuestionFormActions = require('trc-client-core/src/qanda/QandaEditQuestionFormActions');
var LoadingActions = require('trc-client-core/src/global/LoadingActions');
function ifEmpty(message) {
return function (val) {
if (_.isEmpty(val)) {
return message;
}
};
}
var QandaEditQuestionForm = Reflux.createStore({
listenables: [
QandaActions,
QandaEditQuestionFormActions
],
mixins: [ImmutableStoreMixin],
validators: {
questionTitle: ifEmpty('You must supply a title'),
answer: ifEmpty('You must supply a answer'),
askedBy: ifEmpty('Required'),
icon: ifEmpty('Please choose an icon'),
tags: function(item) {
if(!item || (item && item.size === 0)) {
return 'Please choose some tags to categorise this answer';
}
},
answeredBy: ifEmpty('Required')
},
init: function () {
this.listenTo(QandaStore, this.updateQuestion);
this.setState({
question: {},
errors: {},
dirty: false,
icons: {
E308: {icon: 'E308', name: 'Passive Safety'},
E029: {icon: 'E029', name: 'Cars'},
E281: {icon: 'E281', name: 'Service'},
E328: {icon: 'E328', name: 'Design'},
E332: {icon: 'E332', name: 'Efficiency'},
E431: {icon: 'E431', name: 'Active Safety'},
E051: {icon: 'E051', name: 'TFL'},
E318: {icon: 'E318', name: 'Economy'}
}
});
},
onCancelQuestionForm: function () {
this.updateCurrentQuestion();
},
onUpdate: function (e, details) {
var value = Immutable.fromJS(details.value);
var error;
if(this.validators[details.key]) {
error = this.validators[details.key](value);
}
this.setState({
question: this.state.get('question').set(details.key, value),
errors: this.state.get('errors').set(details.key, error),
dirty: true
});
},
onSave: function () {
var model = this.state.get('question');
if(this.checkValidation()) {
if(model.get('id')) {
QandaActions.saveQuestion(model.toJS());
} else {
QandaActions.createQuestion(model.toJS());
}
this.setState({dirty: false});
} else {
LoadingActions.flashMessage('failure long', 'The form still has some errors.', 5000);
}
},
updateQuestion: function() {
this.setState({question: QandaStore.get('question')});
},
checkValidation: function() {
var errors = {};
_.forEach(this.validators, function(func, key){
var message = func(this.state.get('question').get(key));
if(message) {
errors[key] = message;
}
}.bind(this));
this.setState({errors: errors});
return !Object.keys(errors).length;
}
});
module.exports = QandaEditQuestionForm;