Skip to content

Instantly share code, notes, and snippets.

@martletandco
Created July 19, 2017 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martletandco/9f1eb411354e8ea34e6f1098af053cb2 to your computer and use it in GitHub Desktop.
Save martletandco/9f1eb411354e8ea34e6f1098af053cb2 to your computer and use it in GitHub Desktop.
Ember: Proxy actions to plain methods
// Usable with Route, Controller, and Component (anything using `ActionHandler`)
export default Mixin.create({
// Could add to `mergedProperties`
actionsList: [],
// If an action isn't found on the `actions` hash then ActionHandler will check for a target with a send method
// The `computed` allows the correct `this` scope to be used when calling methods
target: computed(function() {
let send = (...args) => {
let methodName = args.shift();
let method = this[methodName];
// Check against allowed list of actions to resist abuse
if(!this.actionsList.includes(methodName) || typeof method !== 'function') {
// Ensure action bubbles (default behaviour)
return true;
}
// Call method as action
return this[methodName](...args) === true;
};
return {
send,
};
}),
});
import ActionProxyMixin from '../mixins/action-proxy';
export default Component.extend(ActionProxyMixin, {
on: false,
// If you had a lot of actions to manage, you could use a decorator system, e.g. `@action methodAsAction(){}`
actionsList: ['toggleAsMethod'],
toggleAsMethod() {
this.toggleProperty('on');
},
actions: {
toggleAsAction() {
this.toggleProperty('on');
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment