【问题标题】:Ember 2.5 observe session property changesEmber 2.5 观察会话属性变化
【发布时间】:2017-04-08 18:18:52
【问题描述】:

我已经为我的路由器打了猴子补丁,以将当前路由组件存储在会话变量中:

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 上找到解决方案。

谢谢!

【问题讨论】:

    标签: session ember.js observers


    【解决方案1】:

    也许考虑使用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 来演示这个解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2018-04-10
      • 2013-10-24
      相关资源
      最近更新 更多