Ember.js依赖注入

Ember.js dependency injection

本文关键字:注入 依赖 js Ember      更新时间:2023-09-26

假设我有这个控制器

MyApp.LayoutFooterController = Ember.ObjectController.extend
  formData:
    name: null,
    phone: null,
    message: null
  cleanFormData: ->
    @set('formData.name', null)
    @set('formData.phone', null)
    @set('formData.message', null)
  send: () ->
    @container.lookup('api:contact').send(
       @get('formData.name'),
       @get('formData.phone'),
       @get('formData.message')
    )
    @cleanFormData()

为此,我创建了服务类

MyApp.Api ||= {}
MyApp.Api.Contact = Ember.Object.extend
  init(@$, @anotherDep) ->
  send: (name, phone, message) ->
    console.log name, phone, message

和初始值设定项

Ember.Application.initializer
  name: 'contact'
  initialize: (container, application) ->
    container.register 'api:contact', MyApp.Api.Contact

问题是,我无法弄清楚如何设置容器以便能够通过 Ember 容器init(@$, @anotherDep)解析我的服务类依赖项。

谁能给我解释一下,如何使用 Ember.js依赖注入(或服务定位器,我猜)容器来注入其他库或对象?

也许,我做得一点也不好。

编辑

当我查看 Ember 的容器源代码时,我找到了一个解决方案:

Ember.Application.initializer
  name: 'contact'
  initialize: (container, application) ->
    container.register 'api:contact', { create: () -> new MyApp.Api.Contact(application.$) }

但这干净吗?

一般来说,你不想自己连接所有的部件,你想在你的控制器中使用needs让 Ember 为你做这件事。 我完全不确定 Ember 如何处理 3 级类名与 2 级类名,所以我只用两个级别进行演示。 ( MyApp.ApiContact 而不是 MyApp.Api.Contact .) 此外,send 是存在于所有(或几乎所有)对象的本机 Ember 方法,因此您希望改用类似 sendMessage 的东西,这样您就不会最终遇到难以诊断的冲突。 在你告诉Ember你的控制器needs apiContact之后,你可以打电话给this.get('controllers.apiContact')来掌握它。

MyApp.LayoutFooterController = Ember.ObjectController.extend({
  needs : ['apiContact'],
  // All your other stuff here
  sendMessage : function(){
    this.get('controllers.apiContact').sendMessage(...);
  }
});