Class Mixin

public
import Mixin from '@ember/object/mixin';

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

import Mixin from '@ember/object/mixin';

const EditableMixin = Mixin.create({
  edit() {
    console.log('starting to edit');
    this.set('isEditing', true);
  },
  isEditing: false
});
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.

// 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()
});
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();
  })
});
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