Created
July 19, 2017 00:54
-
-
Save martletandco/9f1eb411354e8ea34e6f1098af053cb2 to your computer and use it in GitHub Desktop.
Ember: Proxy actions to plain methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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, | |
}; | |
}), | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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