I'm trying to follow the best practice Ember and their potentiality and this question comes to my mind what is the difference between Mixins and Services and how you are using each of them?
I have some services/mixins and work pretty good but I want to be sure I'm doing it right.
A mixin is when you want different objects to have the same behaviour/data. Say you want several controllers to trigger the same action, but change one argument:
// app/mixins/change-name.js
export default Ember.Mixin.create({
actions: {
changeName(item) {
item.set('name', this.get('name'));
}
}
});
// app/controllers/some-controller
import ChangeName from '<app-name>/mixins/change-name';
export default Ember.Controller.extend(ChangeName, {
name: 'Some Controller'
});
Notice that the controllers will have the same action, but it's not shared, each has its own. You can also extend mixins from the object itself since they're added to the _super()
chain.
One gotcha to keep in mind is that primitive by-reference data types like the array are still pass by reference. So if you have a Mixin with an array property, make sure to use Ember.computed
on the array to create new instances each time the Mixin is used. Otherwise simply using a generic []
will lead to all the Mixin uses pointing to the same array. Different reference values, all pointing to the same thing.
Services can be seen as a sort of mutable shared data. If you have a set of data or behaviour that needs to be accessed from different parts of your application, it's a good candidate for a service.
One such example would be a shopping basket, for example. Regardless of where you are in your application, you will need to refer to the same shopping basket in order to manipulate its data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With