Search code examples
ember.jsmixins

Ember: overriding property from imported mixin?


I have a simple mixin that uses a property to perform an action. I'm trying to model inheritance so that I can override this property in the Component that uses the mixin.

For the same benefit of overriding in any OO language.

I appreciate using extend may be preferable for modelling inheritance but I wonder if this is possible with a mixin.


I have tried using this.get('') to retrieve a property from my component that doesn't exist in the mixin. The idea being I can check if the programmer wants to specify the element to focus. If not, use a default. This returns nothing even when the property is defined on the implementing component.

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

export default Mixin.create({
  didRender() {
    this._super(...arguments);
    $(this.get('elementToFocus') ? this.get('elementToFocus') : 'h1').focus();
  }
});

I have also tried using a property on the mixin and then duplicating the property in the component. This breaks everything and gives me random errors.

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

export default Mixin.create({
  elementToFocus: 'h1',
  didRender() {
    this._super(...arguments);
    $(this.get('elementToFocus')).focus();
});

If you can see what I'm trying to achieve, what's the best way to do this?


Solution

  • Thanks guys for your comments. They seem to confirm my suspicions that much of what I was trying / had tried SHOULD have worked.

    My friend got it to work using const focusElement = document.querySelector(this.elementToFocus);

    I'm not sure what I was doing wrong.