【问题标题】:Dependency injection or Service location with RequireJsRequireJs 的依赖注入或服务定位
【发布时间】:2013-06-28 11:48:41
【问题描述】:

我对如何使用 RequireJs 实例化我的对象有点困惑。我正在使用将所有对象定义为类型函数的咖啡脚本类? (不确定术语是否正确)

目前我正在为自己的对象使用依赖注入,这是一个示例 viewModel 和服务

我通过选项数组将我的服务注入到构造函数中的视图模型中

define 'myViewModel', [ 'jquery', 'sammy' ], ( $, sammy ) ->
  class myViewModel
    constructor: ( options ) ->
      self = @
      @service = options.service

      @router = sammy( -> 
        @get( '/SomeRoute#:id', self.onHashUpdated )
      )
      @router.run()

这里我将alertId注入到服务中

define 'myService', ['baseService'], ( baseService ) ->
  class myService extends baseService
    constructor: ( options ) ->
      @alertId = options.alertId
      super()    

这是我的高级页面对象。我进行视图模型实例化并将所有需要的依赖项注入到视图模型中。

require [ 'myViewModel', 'myService', 'domReady!' ], ( viewModel, service ) ->
  myViewModelInstance = new viewModel
    service: new service
      alertId: 'some-alert-id'

我只是不确定我是否应该这样做,或者我是否应该从服务定义中返回一个新服务,使其成为单例。

jquerysammyknockout 等所有其他依赖项都像这样工作,并从 require 返回工作对象,而不是像我的对象那样需要实例化的类型。

是否有使用 requireJs 的公认模式?

我应该进行依赖注入还是服务定位?


这导致测试 javascript 并找到一个可以覆盖 requireJs 并返回模拟对象而不是真正的依赖项的库。

在 Jasmine 中我可能会有这样的东西

describe '=== my view model ===', ->
  sut = null

  beforeEach ->
    require ['myViewModel', 'mockService'], ( viewModel, mockService ) ->
      sut = new viewModel
        service: new mockService

我试用了testr,但文档很糟糕,并且没有任何完整的使用示例。

SquireJs 看起来也有这种可能性?

【问题讨论】:

    标签: dependency-injection coffeescript requirejs jasmine service-locator


    【解决方案1】:

    我已经完成了以下操作,让每个对象实例化它自己的依赖项

    define 'myService', ['baseService', 'alert'], ( baseService, alert ) ->
      class myService extends baseService
        constructor: ( options ) ->
          super()
          @alertId = new alert
    

    然后在我测试模块时使用 squire js 注入 sinon js 模拟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多