rafal_zonk
rafal_zonk

Reputation: 76

Ember.js Observer

I want to use observer on a variable which is in service, that's my code:

const get = Ember.get;

uploader:Ember.inject.service('uploader'),

progressChanged: Ember.observer(this.get('uploader').get('progress'), function() {
  console.log('observer is called', this.get('uploader').get('progress'));
}),

That's the error:

Error while processing route: index this.get is not a function

When I'm trying to show the progress in alert:

actions:
    {
        getProgress()
        {
            alert("progress:"+this.get('uploader').get('progress'));
        }
    }

Everything works, but not in an observer. What should I do?

Upvotes: 0

Views: 372

Answers (1)

Ember Freak
Ember Freak

Reputation: 12872

this context is not valid one. Like Kitler suggested, The below should solve your problem.

import Ember from 'ember';

export default Ember.Component.extend({
    uploader:Ember.inject.service(),//if service name is uploader
    progressChanged: Ember.observer('uploader.progress',function() {
        console.log('observer is called', this.get('uploader').get('progress'));
    }),
});

I would suggest not to overuse observer, you can try using computed property. If you just want to show progress alone then you dont need observer, you can simply use this.get('uploader.progress') or through Ember.computed.alias('uploader.progress').

Reference: https://guides.emberjs.com/v2.7.0/object-model/observers/

Upvotes: 1

Related Questions