Note that there are some explanatory texts on larger screens.

plurals
  1. PODependency injection or Service location with RequireJs
    text
    copied!<p>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)</p> <p>At the moment I'm using dependency injection for my own objects, here's an example viewModel and service</p> <p>I inject my service into the view model in the constructor through an options array</p> <pre><code>define 'myViewModel', [ 'jquery', 'sammy' ], ( $, sammy ) -&gt; class myViewModel constructor: ( options ) -&gt; self = @ @service = options.service @router = sammy( -&gt; @get( '/SomeRoute#:id', self.onHashUpdated ) ) @router.run() </code></pre> <p>Here I inject the alertId into the service</p> <pre><code>define 'myService', ['baseService'], ( baseService ) -&gt; class myService extends baseService constructor: ( options ) -&gt; @alertId = options.alertId super() </code></pre> <p>Here is my high-level page object. I do my view model instantiation and inject all the require dependencies into the view model.</p> <pre><code>require [ 'myViewModel', 'myService', 'domReady!' ], ( viewModel, service ) -&gt; myViewModelInstance = new viewModel service: new service alertId: 'some-alert-id' </code></pre> <p>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.</p> <p>All the other dependencies like <code>jquery</code>, <code>sammy</code>, <code>knockout</code> all work like this and return working objects from <code>require</code> rather than types that need to be instantiated like my objects.</p> <p>Is there an accepted pattern for using requireJs? </p> <p>Should I be doing dependency injection or service location? </p> <hr> <p>This leads onto testing the javascript and finding a library which can override requireJs and return mocked objects instead of the real dependencies. </p> <p>In Jasmine I might have something like this</p> <pre><code>describe '=== my view model ===', -&gt; sut = null beforeEach -&gt; require ['myViewModel', 'mockService'], ( viewModel, mockService ) -&gt; sut = new viewModel service: new mockService </code></pre> <p>I tried out <a href="https://github.com/mattfysh/testr.js" rel="nofollow">testr</a> but the documentation is abysmal and there's not really any full examples of how to use it.</p> <p><a href="https://github.com/iammerrick/Squire.js/" rel="nofollow">SquireJs</a> looks like a possibility too for this kind of thing?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload