Skip to content

Instantly share code, notes, and snippets.

@spieker
Last active December 5, 2016 10:26
Show Gist options
  • Save spieker/5e3dfb7a33712fd0ef406772f76c2603 to your computer and use it in GitHub Desktop.
Save spieker/5e3dfb7a33712fd0ef406772f76c2603 to your computer and use it in GitHub Desktop.
Translated attribute for ember-data
import Transform from 'ember-data/transform';
export default Transform.extend({
deserialize(serialized) {
return Ember.Object.create(serialized);
},
serialize(deserialized) {
return deserialized;
}
});
import Ember from 'ember';
const {
computed
} = Ember;
/**
* translatedAttribute - Creates a translated version of the given attribute.
* The locale used to be get/set must be provided on the `_locale` property of
* the model.
*
* ```js
* import Model from 'ember-data/model';
* import translated from 'admin/utils/translated-attribute';
* import { attr } from 'ember-computed-decorators/ember-data';
*
* export default Model.extend({
* // Attributes
* //
* @attr('string') slug,
* @attr('localized') titleTranslations,
* @attr('localized') contentTranslations,
* // Translations
* //
* _locale: 'en',
* @translated('title') title,
* @translated('content') pageContent
* });
* ```
*
* @param {String} attribute source attribute
* @public
*/
export default function translatedAttribute(attribute) {
return function(target, key, descriptor) {
let translationsKey = `${attribute}Translations`;
return {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
initializer() {
return computed('_locale', translationsKey, {
get() {
let locale = this.get('_locale');
return this.get(`${translationsKey}.${locale}`);
},
set(name, value) {
let current = this.get(translationsKey);
if (!current) {
this.set(translationsKey, Ember.Object.create());
}
let locale = this.get('_locale');
let result = this.set(`${translationsKey}.${locale}`, value);
this.notifyPropertyChange(translationsKey);
return result;
}
});
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment