How to define an Observer in an Ember Octane model?

50 Views Asked by At

After being a long-term Ember 2.x user on a long-neglected project, I'm going through the process of updating it to a more modern version of Ember; in this case 4.12. I'm getting hung up on one of the changes though:

I've defined a model using the Octane style of class definition:

// app/models/widget.js

import Model, { attr } from '@ember-data/model';
import { observer } from '@ember/object';
import { service } from '@ember/service';

export default class Widget extends Model {
  @service eventTracking;

  @attr('boolean', { defaultValue: false }) locked;
  @attr('number') partnerId;

  ...

  @observer('locked') lockedChanged() {
    this.eventTracking.trackWidgetUpdated(this);
  }
}

I figured this would work since it follows the newer way of defining attributes, services, etc. in Octane classes, but I'm getting this error in the console:

Uncaught Error: Assertion Failed: observer must be provided a function or an observer definition

Is this format not supported, and if I want to use an Observer, I need to use the traditional Model.extend({ ... }) syntax instead? Or am I just doing something wrong here?

P.S. I understand that generally, Ember is moving away from Observers, but I have a use case where an Observer is exactly what I need; anytime the locked attribute changes, we want to call a service function to note the change. I'm open to other suggestions, though, if they exist. If there is some other callback I can use that's called whenever the locked attribute changes value, that would be great too. But it'll be a bit onerous to manually call the service anytime the value is changed, so I'd like to avoid that if possible.

0

There are 0 best solutions below