Skip to content

Instantly share code, notes, and snippets.

@mrosata
Last active August 20, 2016 12:33
Show Gist options
  • Save mrosata/c2b8efc263ca0ab3321221091baea89d to your computer and use it in GitHub Desktop.
Save mrosata/c2b8efc263ca0ab3321221091baea89d to your computer and use it in GitHub Desktop.
Ember partial getter and setter. A functional style get(this, 'prop') and set(this, 'prop', val) that also supports partial arguments by returning functions when supplied less arguments then required on the first call.
/**
* Ember
* (more functional style) Getter and Setter
*
* setup option 1 (modular):
* const {get, set} = getSetterDecorator();
* setup option 2 (global):
* getSetterDecorator( window );
*/
import Ember from 'ember';
export default function getSetterDecorator ( namespace = {}, setKey = 'set', getKey = 'get' ) {
namespace[ getKey ] = partialEmberGetter;
namespace[ setKey ] = partialEmberSetter;
return namespace;
}
/** Getter **/
function partialEmberGetter ( context, property ) {
if ( arguments.length === 1 ) {
return (prop) => Ember.get.call( context, context, prop );
}
return Ember.get.call( context, context, property );
}
/** Setter **/
function partialEmberSetter ( context, property, value ) {
switch ( arguments.length ) {
case 1:
return function ( ) {
return partialEmberSetter.apply( context, [context, ...arguments] );
};
case 2:
return ( value ) => Ember.set.call( context, context, property, value );
}
return Ember.set.apply( context, arguments );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment