Last active
December 16, 2015 22:09
-
-
Save milankinen/5505385 to your computer and use it in GitHub Desktop.
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
# PART 1: tweak backbone validation a little bit | |
# =============================================== | |
# first, allow errorous inputs to update our model | |
Backbone.Validation.configure | |
forceUpdate: true | |
# then disable default callbacks for backbone validation events | |
_.extend Backbone.Validation.callbacks, | |
valid: (view, attr, selector) -> | |
# these are not used | |
invalid: (view, attr, error, selector) -> | |
# these are not used | |
# we are using our custom model events "valid:<attr>" and "invalid:<attr>" to indicate | |
# when model field is validated | |
attrValid = (view, attr, selector) -> | |
# 'view' is not used, views use our implementation ;) | |
@trigger "valid:#{attr}", attr, selector | |
attrInvalid = (view, attr, errorMsg, selector) -> | |
# 'view' is not used, views use our implementation ;) | |
@trigger "invalid:#{attr}", attr, errorMsg, selector | |
origValidate = Backbone.Validation.mixin.validate | |
Backbone.Validation.mixin.validate = (attrs, setOptions) -> | |
options = setOptions || {} | |
# "this" refers now to model so we apply it to our validation | |
# functions, thus can trigger validation events for right model | |
options.valid = => attrValid.apply(@, arguments) | |
options.invalid = => attrInvalid.apply(@, arguments) | |
origValidate.call(@, attrs, options) | |
# add customized validation to our models, when validations occur, they raise | |
# model events valid:<attr> and invalid:<attr> to our models. Views may be interested | |
# in those validation callbacks for showing error messages. | |
_.extend(Backbone.Model.prototype, Backbone.Validation.mixin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment