mardi 13 novembre 2018

Ember: Why does computed not fire when the observer does?

I'm having difficulty wrapping my head around this - I'm working with inherited legacy code, and while this seems like it should be very simple, it's anything but.

In this app/pods/application/route.js, there's a "welcome pack" object that's grabbed by the server, as part of that, there's a setWp() method called on the welcome-pack service, which sets the 'wp' value on that same service. (Yes, I know you can probably set the value on the service directly, with "this.wp.set('wp', welcomePack)" but as I said: inherited legacy code.) Point is, that should trigger the change in the value. My observer for wp.wp is firing, but NOT my computeds based on wp.wp. Any clues?

// app/pods/application/route.js
wp: inject('welcome-pack'),
model(){
  return this.store.findAll('welcome-pack').then((welcomePack) => {
  this.wp.setWp(welcomePack);
})
}



// app/pods/welcome-pack/service.js
import Service from '@ember/service';
export default Service.extend({
  wp: null,
  setWp(wp){ // <-- called when the model loads from the ajax request
    this.set('wp', wp)
  }
})

// app/pods/application/controller.js
import Controller from "@ember/controller";
import { inject } from "@ember/service";
import { computed, observer } from "@ember/object";

export default Controller.extend({
  wp: inject("welcome-pack"),
  init(){
    console.log('this.wp', this.wp) // <- logs service as class
    console.log('this.wp.wp', this.wp.wp) // <-logs null
    setTimeout(() => {
      // set for after the ajax call has been made and setWp() has been called. 
      console.log('this.wp', this.wp) //<- logs service as class
      console.log('this.wp.wp', this.wp.wp) //<- logs object as class
    }, 2000)
  },
  obsWPChanges: observer('wp', function(){
    console.log('wp changed'); // <-- never executes (don't expect it to)
  }),
  obsWPWPChanges: observer('wp.wp', function(){
    console.log('wp.wp changed') //<-- executes (as expected) when setWP() is called
  }),
  primaryColor: computed("wp.wp", function() {
    console.log("this.wp.primaryColor", this.wp.primaryColor) // <-- does not execute
    return this.wp.wp.primaryColor || "#37b3c0";
  }),
  secondaryColor: computed("wp.wp", function() {
    return this.wp.wp.secondaryColor || "#38a0d0"; // <-- does not execute
  })
});




Aucun commentaire:

Enregistrer un commentaire