Skip to content

Instantly share code, notes, and snippets.

@lifeinafolder
Created September 17, 2013 05:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lifeinafolder/6590390 to your computer and use it in GitHub Desktop.
Save lifeinafolder/6590390 to your computer and use it in GitHub Desktop.
Ember Input Fields with character limits
UiControls = window.UiControls || Ember.Namespace.create();
/**
* A MaxLength UI Control
* It extends your regular INPUT[type='text'] & TEXTAREA fields
* to support a character count on them
*
* @class
* @memberOf UiControls
* @extends Ember.View
*/
UiControls.InputMaxLength = Ember.View.extend({
layout: Ember.Handlebars.compile('<p>{{view.label}}<span {{bindAttr class="view.isCharLimitReached :char-count"}}>{{view.message}}</span>{{yield}}</p>'),
template: function () {
switch (this.get('type')) {
case 'textarea':
return Ember.Handlebars.compile('{{view Ember.TextArea viewName="inputControl" valueBinding="view.value" placeholderBinding="view.placeholder" maxlengthBinding="view.maxlength"}}');
break;
default:
return Ember.Handlebars.compile('{{view Ember.TextField viewName="inputControl" valueBinding="view.value" placeholderBinding="view.placeholder" maxlengthBinding="view.maxlength"}}');
}
}.property(),
classNames: ['uicontrol-input-maxlength'],
/**
* Type of Input Field
* By default - its a text input
* To use it with a textara, specify type as 'textarea'
* @type {String} ['textarea']
*/
type: null,
/**
* Current value of the input field
* @type {String|Number}
*/
value: null,
/**
* Label associated with 'INPUT' field
* @required
* @type {String}
*/
label: null,
/**
* Placeholder string of 'Input' field
* @optional
* @type {String}
*/
placeholder: null,
/**
* HTML5 MaxLength attribute of 'Input' field
* @required
* @type {String}
*/
maxlength: null,
/**
* character count message we show
* @private
* @type {String}
*/
message: null,
currentCountBinding: 'inputControl.value.length',
charactersLeft: function () {
return this.get('maxlength') - this.get('currentCount');
}.property('currentCount'),
isCharLimitReached: Ember.computed.equal('charactersLeft', 0),
keyUp: function () {
this.set('message', this.get('charactersLeft') + ' Characters Left');
},
didInsertElement: function () {
if (!this.get('maxlength')) {
Ember.assert('UiControls.InputMaxLength doesn\'t work without a maxlength attribute');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment