JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-1.0.pre.min.js"></script>
<script type="text/x-handlebars">
{{view App.UsernameField}}
</script>
CSS
.error .controls {
color: red;
}
.success .controls {
color: green;
}
CoffeeScript
window.App = Ember.Application.create()
App.TextField = Ember.TextField.extend
focused: false
focusIn: (event) ->
@set 'focused', true
focusOut: (event) ->
@set 'focused', false
App.UsernameField = Ember.View.extend
classNames: ['control-group']
classNameBindings: ['status']
focused: false
currentValue: ""
status: (->
# If field is focused or empty
return '' if @get('focused') or not @get('currentValue')
return 'error' if @get('currentValue').length < 4
return {
available: 'success'
unavailable: 'error'
unknown: ''
}[@get('isAvailable')]
).property 'isAvailable', 'currentValue', 'focused'
helpText: (->
# If field is focused or empty
return '' if @get('focused') or not @get('currentValue')
if @get('currentValue').length < 4
return 'Username too short'
return {
available: 'Username is available'
unavailable: 'Username is unavailable'
unknown: ''
}[@get('isAvailable')]
).property 'isAvailable', 'currentValue', 'focused'
ajaxValue: null
isAvailable: 'unknown'
checkAvailability: (->
currentValue = @get 'currentValue'
ajaxValue = @get 'ajaxValue'
# If value of the text field has changed
if currentValue != ajaxValue
# Invalidate the lookup
@set 'ajaxValue', null
@set 'isAvailable', 'unknown'
# If the field is blurred
if not @get 'focused'
# Do a new lookup
@set 'ajaxValue', currentValue
self = this
setTimeout((->
# If the email in the field is the same as the one we were testing
if self.get('ajaxValue') == currentValue
self.set 'isAvailable', 'available'
), 1000)
).observes 'currentValue', 'focused'
template: Ember.Handlebars.compile """
<div class="controls">
{{view App.TextField
placeholder = "Email"
valueBinding = "view.currentValue"
focusedBinding = "view.focused"
}}
<span...