Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's difference between Mixins and Services on Emberjs

Tags:

ember.js

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.

like image 547
DeivinsonTejeda Avatar asked Feb 08 '16 12:02

DeivinsonTejeda


1 Answers

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.

like image 149
locks Avatar answered Nov 19 '22 05:11

locks