Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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