Skip to content

Instantly share code, notes, and snippets.

@zomarg
Forked from GavinJoyce/controllers.application.js
Created February 2, 2017 20:28
Show Gist options
  • Save zomarg/11937b5924529f995351b177b456df61 to your computer and use it in GitHub Desktop.
Save zomarg/11937b5924529f995351b177b456df61 to your computer and use it in GitHub Desktop.
Dynamic key validation
import Em from 'ember';
//Ember Computed Factory Macro
function is(type, dependentKey){
console.log(type);
console.log(dependentKey);
let computed = Ember.A();
for(var i=0; i<=type.length; i++){
switch(type)
{
case "numeric":
computed.push(Ember.computed(dependentKey, function(){
return Ember.$.isNumeric(this.get(dependentKey));
}));
break;
case "notEmpty":
computed.push(Ember.computed.notEmpty(dependentKey));
break;
default:
throw new Error("error");
break;
}
}
return Ember.computed(function() {
for(let i=0; i<=computed.length; i++){
this.computed[i]();
}
});
}
//is(['numeric', 'text', 'notEmpty'], 'text');
export default Em.Controller.extend({
useAdditionalValidators: false,
text: '',
hasText: is("numerisc", 'text'),
isNumber: is('numeric', 'text'),
validators: Em.computed('useAdditionalValidators', function() {
if(this.get('useAdditionalValidators')) {
return ['hasText', 'isNumber'];
} else {
return ['hasText'];
}
}),
//TODO: create something that allows us to remove 'hasText', 'isNumber' keys
isValid: Em.computed('validators.[]', 'hasText', 'isNumber', function() {
return this.get('validators').every(v => this.get(v) === true);
})
});
<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