Class Mixin

public
Module: @ember/object
Since: v3.1.3

The Mixin class allows you to create mixins, whose properties can be added to other classes. For instance,

1
2
3
4
5
6
7
8
9
import Mixin from '@ember/object/mixin';

const EditableMixin = Mixin.create({
  edit() {
    console.log('starting to edit');
    this.set('isEditing', true);
  },
  isEditing: false
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import EmberObject from '@ember/object';
import EditableMixin from '../mixins/editable';

// Mix mixins into classes by passing them as the first arguments to
// `.extend.`
const Comment = EmberObject.extend(EditableMixin, {
  post: null
});

let comment = Comment.create({
  post: somePost
});

comment.edit(); // outputs 'starting to edit'

Note that Mixins are created with Mixin.create, not Mixin.extend.

Note that mixins extend a constructor's prototype so arrays and object literals defined as properties will be shared amongst objects that implement the mixin. If you want to define a property in a mixin that is not shared, you can define it either as a computed property or have it be created on initialization of the object.

1
2
3
4
5
6
7
// filters array will be shared amongst any object implementing mixin
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';

const FilterableMixin = Mixin.create({
  filters: A()
});
1
2
3
4
5
6
7
8
9
10
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';
import { computed } from '@ember/object';

// filters will be a separate array for every object implementing the mixin
const FilterableMixin = Mixin.create({
  filters: computed(function() {
    return A();
  })
});
1
2
3
4
5
6
7
8
9
10
11
12
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';

// filters will be created as a separate array during the object's initialization
const Filterable = Mixin.create({
  filters: null,

  init() {
    this._super(...arguments);
    this.set("filters", A());
  }
});

Show:

Methods

No documented items

Properties

No documented items

Events

No documented items