Skip to content

Instantly share code, notes, and snippets.

@lekodeveloperweb
Forked from alexbeletsky/Feedback.js
Created January 26, 2016 16:42
Show Gist options
  • Save lekodeveloperweb/edb225cc6dd55244d8f7 to your computer and use it in GitHub Desktop.
Save lekodeveloperweb/edb225cc6dd55244d8f7 to your computer and use it in GitHub Desktop.
Baby steps to Backbone - step 2 - Validation
var Feedback = Backbone.Model.extend({
url: '/feedback',
defaults: {
'email': '',
'website': '',
'feedback': ''
},
validate: function (attrs) {
var errors = [];
if (!attrs.email) {
errors.push({name: 'email', message: 'Please fill email field.'});
}
if (!attrs.feedback) {
errors.push({name: 'feedback', message: 'Please fill feedback field.'});
}
return errors.length > 0 ? errors : false;
}
});
$(function () {
var model = new Feedback();
var view = new FeedbackFormView ({model: model});
$('#app').html(view.render().el);
});
var FeedbackFormView = Backbone.View.extend({
className: 'row',
template: '\
<form>\
<legend>Share the feedback</legend>\
<div class="control-group email">\
<label>Email</label>\
<input type="text" id="email" placeholder="Your email address...">\
<span class="help-inline"></span>\
</div>\
<div class="control-group website">\
<label>Web site</label>\
<input type="text" id="website" placeholder="Your website...">\
<span class="help-inline"></span>\
</div>\
<div class="control-group feedback">\
<label>Feedback</label>\
<textarea id="feedback" class="input-xxlarge" placeholder="Feedback text..." rows="6"></textarea>\
<span class="help-inline"></span>\
</div>\
<button type="submit" id="submit" class="btn">Submit</button>\
</form>\
',
events: {
'click #submit': 'submitClicked'
},
render: function () {
this.$el.html(this.template);
return this;
},
submitClicked: function (e) {
e.preventDefault();
var me = this;
var options = {
success: function () {
me.hideErrors();
},
error: function (model, errors) {
me.showErrors(errors);
}
};
var feedback = {
email: this.$('#email').val(),
website: this.$('#website').val(),
feedback: this.$('#feedback').val()
};
this.model.save(feedback, options);
},
showErrors: function(errors) {
_.each(errors, function (error) {
var controlGroup = this.$('.' + error.name);
controlGroup.addClass('error');
controlGroup.find('.help-inline').text(error.message);
}, this);
},
hideErrors: function () {
this.$('.control-group').removeClass('error');
this.$('.help-inline').text('');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment