Skip to content

Instantly share code, notes, and snippets.

@GavinJoyce
Forked from nolaneo/controllers.application.js
Last active February 2, 2017 20:28
Show Gist options
  • Save GavinJoyce/9ff41b7ded2476c9c330f20498f5d310 to your computer and use it in GitHub Desktop.
Save GavinJoyce/9ff41b7ded2476c9c330f20498f5d310 to your computer and use it in GitHub Desktop.
Dynamic key validation
import Em from 'ember';
export default Em.Controller.extend({
useAdditionalValidators: false,
text: '',
hasText: Em.computed.notEmpty('text'),
isNumber: Em.computed('text', function() {
return Em.$.isNumeric(this.get('text'));
}),
validators: Em.computed('useAdditionalValidators', function() {
if(this.get('useAdditionalValidators')) {
return ['hasText', 'isNumber'];
} else {
return ['hasText'];
}
}),
//TODO: GJ: extract to macro
validatorObserver: function() {
let validators = this.get('validators');
console.log('GJ: validators', validators);
Em.defineProperty(this, 'isValid', Em.computed(...validators, function() {
return this.get('validators').every(v => this.get(v) === true);
}));
this.notifyPropertyChange('isValid');
}.observes('validators').on('init')
});
<h3>Validators</h3>
useAdditionalValidators: {{input type='checkbox' checked=useAdditionalValidators}}
<br /><br />
{{#each validators as |validator|}}
[{{validator}}]
{{/each}}
<h3>Input:</h3>
{{input value=text}}
{{#if isValid}}
<h1 style="color: darkgreen">Valid :-)</h1>
{{else}}
<h1 style="color: red">Invalid :-(</h1>
{{/if}}
{
"version": "0.10.7",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.10.0",
"ember-data": "2.10.0",
"ember-template-compiler": "2.10.0",
"ember-testing": "2.10.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment