Pass service functions like closure actions into components.
ember install ember-service-function-helper
service-function
takes two or more arguments:
- Name of service
- Name of function defined in service
- Argument to pass to function
In use, it looks like this:
To use this directly in a template as the result of an onclick
or something
similar:
// my-service.js
import { A } from '@ember/array';
import Service from '@ember/service';
export default Service.extend({
state: null,
init() {
this.set('state', A(['a']));
this._super(...arguments);
},
addToState(toAdd) {
this.get('state').pushObject(toAdd);
}
});
You can also pass it into a component just like you would a closure action:
You could then use this as the result of some user event inside of my-component
like so:
Alternatively, you could do this:
// my-component.js
import Component from '@ember/component';
export default Component.extend({
actions: {
do (thing) {
// Note: `this.get('do')(thing)` will not work!
this.do(thing);
}
}
});
It then follows that something like this could work, too:
You can also curry arguments just like with the action
helper:
// my-service.js
import { A } from '@ember/array';
import Service from '@ember/service';
export default Service.extend({
state: null,
init() {
this.set('state', A(['a']));
this._super(...arguments);
},
addThreeToState(one, two, three) {
this.get('state').pushObject(one);
this.get('state').pushObject(two);
this.get('state').pushObject(three);
}
});
- You can avoid
inject
ing services into controllers or components - You can avoid writing wrapper
actions
aroundservice
functionality - This can decouple component behavior from implementation
- You can mock less services in tests
git clone <repository-url>
cd ember-service-function-helper
npm install
npm run lint:js
npm run lint:js -- --fix
ember test
– Runs the test suite on the current Ember versionember test --server
– Runs the test suite in "watch mode"ember try:each
– Runs the test suite against multiple Ember versions
ember serve
- Visit the dummy application at http://localhost:4200.
For more information on using ember-cli, visit https://ember-cli.com/.
This project is licensed under the MIT License.