2016-11-24 79 views
1

我有猴子修補我的路由器當前的路由組件存儲在一個會話變量:灰燼2.5觀察會話屬性更改

var Router = Ember.Router.extend({ 
    customSession: Ember.inject.service('session-custom'), 
    location: config.locationType, 

    didTransition: function() { 
     this._super(...arguments); 

     this.get('customSession').set('currentEntity', this.get('currentRouteName').split('.')[0]); 
     this.get('customSession').set('currentDetailView', this.get('currentRouteName').split('.')[1]); 

    } 
}); 

我知道,這不是最乾淨的解決方案,但是寫會話到控制檯證明至少設置了這些參數。

在我的控制,我想監聽這些參數的變化,但不知何故這不起作用:

import Ember from 'ember'; 
import ApplicationController from './application'; 

export default ApplicationController.extend({ 

    customSession: Ember.inject.service('session-custom'), 

    currentRouteNameChanged: Ember.observer('customSession.currentEntity', function() { 
     console.log("route changed"); 
    }) 
}); 

即「路線改爲」從不打印到控制檯。

這看起來相當簡單,但我一直無法找到SO的解決方案。

謝謝!

回答

0

也許考慮使用initializer將您的session-custom服務注入到您的應用程序的控制器中。爲了達到這個目標,提出了一些建議......

首先,在路由器和其他地方,使用傳統的,駱駝速記注入你的服務,如:

sessionCustom: Ember.inject.service(), 

...並且一定要請在代碼中參考sessionCustom,而不是customSession

接下來,創建一個session-custom初始化,並注入服務到應用程序的控制器:

export function initialize(application) { 
    application.inject('controller', 'sessionCustom', 'service:session-custom'); 
} 

export default { 
    name: 'session-custom', 
    initialize, 
}; 

觀察從控制器路由變化,現在應該是成功的:

export default Ember.Controller.extend({ 
    currentRouteNameChanged: Ember.observer(
    'sessionCustom.currentEntity', function() { 
     console.log("CONTROLLER: ", this.get('sessionCustom.currentEntity')); 
    } 
), 
}); 

這些變化,當然,也可以從服務本身觀察:

export default Ember.Service.extend({ 
    currentEntity: '', // <-- it's helpful to explicitly declare 

    currentRouteNameChanged: Ember.observer(
    'currentEntity', function() { 
     console.log("SERVICE: ", this.get('currentEntity')); 
    } 
), 
}); 

我創建了一個Ember Twiddle來演示此解決方案。