Ember- 1.13服务未在组件中初始化

时间:2015-10-21 16:40:21

标签: javascript ember.js dependency-injection ember-cli

我有一个时钟服务-clock.js

import Ember from 'ember';
var ONE_SECOND = 2000;

export default Ember.Object.extend({
  time : null,
  second : null,
  tick: function() {
    var clock = this;

    Ember.run.later(function () {
      var now = new moment();
      clock.setProperties({
        time : now,
        second : now.seconds()
      });
    }, ONE_SECOND);

  }.observes('second').on('init')
})

我初始化为

export function initialize(container, application) {
  container.optionsForType('service:clock', { singleton: true });
  application.inject('route', 'clockService', 'service:clock');
  application.inject('controller', 'clockService', 'service:clock');
  application.inject('component', 'clockService', 'service:clock');
}

export default {
  name: 'clock-service',
  initialize: initialize
};

我使用时钟自动收报机来计算经过的时间(我正在使用moment.js)。

timeElapsed : function(){
    var clock = this.get('clockService').get('time');
    var createdTime = new moment(this.get('request.createdAt'));
    var duration = moment.duration(clock.diff(createdTime));
    if(duration._data.hours > 0) return duration._data.hours+" hrs";
    if(duration._data.minutes > 0) return duration._data.minutes+" mins";
    if(duration._data.seconds > 0) return duration._data.seconds+" secs";
    return duration._data.seconds;
  }.property('request.createdAt','clockService.second')

现在的问题是服务正在组件中注入,但未设置属性。

1 个答案:

答案 0 :(得分:2)

我能够让它在这里运行,并做了一些修改:
http://emberjs.jsbin.com/sexiqu/1/edit?html,js,output

请查看ClockServiceComponent。

我与你的代码做的唯一不同的是使用带有'clock.time'作为其依赖键的计算属性,因此计算属性将每秒延迟计算。

Ember.Application.initializer({
  name: 'registerClock',

  initialize: function(container, application) {
    application.register('clock:main', Ember.clockService);
  }
});

var ONE_SECOND = 1000;

Ember.clockService = Ember.Service.extend({
  time : null,
  second : null,
  tick: function() {
    var self = this;

    Ember.run.later(function () {
      var now = new moment();
      self.setProperties({
        time: now,
        second: now.seconds()
      });
    }, ONE_SECOND);
  }.observes('second').on('init')
});

Ember.Application.initializer({
  name: 'injectClockService',
  initialize: function(container, application) {
    application.inject('controller', 'clock', 'clock:main');
    application.inject('route',      'clock', 'clock:main');
    application.inject('component',  'clock', 'clock:main');
  }
});

App = Ember.Application.create();
App.Router.map(function() {
  // put your routes here
});

App.IndexRoute = Ember.Route.extend({});

App.ClockServiceComponent = Ember.Component.extend({
  second: Ember.computed('clock.time', function() {
    return this.get('clock.second');
  })
});