在EmberJS中,如果我有一个实用程序类,我通过初始化程序注入容器,如何将依赖项注入该实用程序类?
例如,可以使用此初始化程序注入消息类:
import Messages from 'app/utils/messages';
var injectMessagesInitializer = {
name: 'injectMessages',
before: 'authentication',
initialize: function (container, application) {
application.register('messages:main', Messages, {initialize: false, singleton: true});
application.inject('controller', 'messages', 'messages:main');
application.inject('component', 'messages', 'messages:main');
application.inject('router', 'messages', 'messages:main');
application.inject('route', 'messages', 'messages:main');
}
};
export default injectMessagesInitializer;
现在,我希望能够将Notifier类注入到Messages实用程序中。我可以做类似以下的事情吗?
import Notifier from 'notifier';
var injectNotifierIntoMessagesInitializer = {
name: 'injectNotifierIntoMessages',
after: 'injectMessages',
initialize: function (container, application) {
application.inject('messages', 'notifier', 'notifier:main');
}
};
export default injectNotifierIntoMessagesInitializer;
在实用程序类中:
var Messages = Ember.Object.extend({
showError: function (message, options) {
this.notifier.error(message, options);
},
showErrors: function (errors, options) {
options = options || {};
for (var i = 0; i < errors.length; i += 1) {
this.showError(errors[i].message || errors[i], options);
}
},
...
});
有几点需要注意: