Skip to content

Instantly share code, notes, and snippets.

@insin
Last active August 29, 2015 14:09
Show Gist options
  • Save insin/4cc1bb145fd9d7c583db to your computer and use it in GitHub Desktop.
Save insin/4cc1bb145fd9d7c583db to your computer and use it in GitHub Desktop.
What happens when you design by writing real code against a speculative API first
var SignupForm = form.Form.extend({
  username: forms.CharField(),

  /**
   * @param {function(err, field, errorMessages)} cb
   */
  cleanUsernameAsync: function(cb) {
    // Return false to indicate that no async validation is being performed -
    // this shouldn't be strictly needed for field-specific custom cleaning
    // methods, as they will only be called if the field is valid according to
    // Field validation and clean<Name> validation, BUT you could take advantage
    // of this to combine sync & async validation into the same  custom clean
    // method, calling addError and returning false or throwing a ValidationError
    // before the synchronous part.

HOLD IT

This means we don't need a separate clean<Name>Async(cb) method for this - we can just change the definition for the existing method from clean<Name>() to clean<Name>([cb]) and check its arity!

    if (!this.cleanedData.username) {
      return false
    }

    // Kick async processing off
    var req = superagent.post('/checkusername').send({username: username}).end(
      function(res) {
        // Callback with an Error if things went wrong with the call
        if (!res.ok) {
          return cb(new Error(res.txt))
        }
        // If something is invalid based on the response, callback with arguments
        // for addError().
        if (!res.body.available) {
          return cb(null, 'username', 'This username is already taken.')
        }
        cb(null)
      }
    )

    // Return an object with .onCancel() for pending stuff to be aborted
    return {
      onCancel: req.abort.bind(req)
    }
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment