Question

I'm a little confused about how I should be instantiating my objects with RequireJs. I'm using coffeescript classes which defines all my objects as typed functions? (not sure on the correct terminology)

At the moment I'm using dependency injection for my own objects, here's an example viewModel and service

I inject my service into the view model in the constructor through an options array

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

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

Here I inject the alertId into the service

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

Here is my high-level page object. I do my view model instantiation and inject all the require dependencies into the view model.

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

I'm just not sure if this is how I should be doing it or if I should be returning a new service from the service define making it a singleton.

All the other dependencies like jquery, sammy, knockout all work like this and return working objects from require rather than types that need to be instantiated like my objects.

Is there an accepted pattern for using requireJs?

Should I be doing dependency injection or service location?


This leads onto testing the javascript and finding a library which can override requireJs and return mocked objects instead of the real dependencies.

In Jasmine I might have something like this

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

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

I tried out testr but the documentation is abysmal and there's not really any full examples of how to use it.

SquireJs looks like a possibility too for this kind of thing?

Was it helpful?

Solution

I've gone for the following, having each object instantiate it's own dependencies

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

Then using squire js for injecting sinon js mocks when I'm testing the modules.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top