Last active
October 1, 2015 20:07
-
-
Save stu-smith/2049308 to your computer and use it in GitHub Desktop.
Simple utility methods to copy Backbone models to and from forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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