Skip to content

Instantly share code, notes, and snippets.

@poteto
Last active December 27, 2017 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save poteto/44e1aac8ed7ad53cd45c7419c655e77d to your computer and use it in GitHub Desktop.
Save poteto/44e1aac8ed7ad53cd45c7419c655e77d to your computer and use it in GitHub Desktop.
changeset es6 proxy
import Ember from 'ember';
import Changeset from '../lib/changeset';
import validatePresence from '../validators/presence';
let model = { foo: 'bar' };
let validations = {
foo: validatePresence()
};
let changeset = new Changeset(model, { validations });
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
init() {
this._super(...arguments);
console.log('Model', model);
console.log('Changeset', changeset);
changeset.foo = '';
console.log('changeset.foo value is:', changeset.foo);
changeset.foo = 123;
console.log('changeset.foo value is:', changeset.foo);
}
});
import Ember from 'ember';
import validatorLookup from './validator-lookup';
const { warn } = Ember;
function createChangeset(obj, { validations }) {
return new Proxy(obj, {
set(target, property, value, receiver) {
let validationResult = validatorLookup(validations, property)(property, value);
if (validationResult.isValid) {
target[property] = value;
} else {
warn(validationResult.message);
}
return true;
}
});
}
export default class Changeset {
constructor() {
return createChangeset(...arguments);
}
}
export default class ValidationResult {
constructor(validation, message) {
this.validation = validation;
this.message = message;
}
get isValid() {
return this.validation === true;
}
get isInvalid() {
return !this.isValid;
}
}
export default function validatorLookup(validations, key) {
return typeof validations[key] === 'function' && validations[key];
}
{
"version": "0.12.1",
"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.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1"
}
}
import ValidationResult from '../lib/validation-result';
export default function validatePresence() {
return ((key, value) => {
return new ValidationResult(!!value, `${key} must be present`);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment