Skip to content

Instantly share code, notes, and snippets.

@stu-smith
Last active October 1, 2015 20:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stu-smith/2049308 to your computer and use it in GitHub Desktop.
Save stu-smith/2049308 to your computer and use it in GitHub Desktop.
Simple utility methods to copy Backbone models to and from forms
define([
'jQuery',
'Underscore'
], function ($, _) {
'use strict';
return {
clearForm: function (f) {
$(f).find('input').val('');
},
formToModel: function (form, model) {
var success = true,
jform = $(form);
jform.find('.help-inline').remove();
jform.find('.control-group').removeClass('error');
jform.find('[data-bind]').each(function (i, elem) {
var jelem = $(elem),
attr = jelem.data('bind'),
val = {};
val[attr] = jelem.val();
model.set(val, {
error: function (m, err) {
var helpInline = $('<span class="help-inline"></span>').text(err);
jelem.after(helpInline);
jelem.closest('.control-group').addClass('error');
if (success) {
jelem.focus();
}
success = false;
}
});
});
return success;
},
modelToForm: function (model, form) {
$(form).find('[data-bind]').each(function (i, elem) {
var attr = $(elem).data('bind');
$(elem).val(model.get(attr));
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment