简体   繁体   中英

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM