DeivinsonTejeda February 2016

What's difference between Mixins and Services on Emberjs

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.

Answers


locks February 2016

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.

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.

Post Status

Asked in February 2016
Viewed 3,305 times
Voted 9
Answered 1 times

Search




Leave an answer