There are a couple of ways to create multiple component instances in wire.js. Depending on your needs you can see which one might work for you.
First, you can use the create
factory to beget new instances from a prototype. When you give create
a function or constructor module, it will call them. However, if you give create
an existing object, it will use Object.create
to beget a new instance, which you can then further configure as usual (e.g. using properties
, init
, advices, etc.). Just keep in mind that it works exactly like Object.create
, so prototype properties will be shared.
Second, you can use the wire
factory to achieve the effect you're after, though. You just need to wrap the non-singleton in its own wire spec. Here's a quick example:
thingThatNeedsATrackingService: {
create: 'my/ThingThatNeedsATrackingService',
properties: {
foo: { wire: 'my/trackingServiceSpec' }
}
},
otherThingThatNeedsATrackingService: {
create: 'my/OtherThingThatNeedsATrackingService',
properties: {
foo: { wire: 'my/trackingServiceSpec' }
}
},
//... more components
And then, in my/trackingService.js
:
// Export the trackingService instance
$exports: { $ref: 'trackingService' },
trackingService: {
create: {
module: 'Bnaya/App/TrackingService',
args: []
}
},
//... more components if you need
That will inject a new instance of a Bnaya/App/TrackingService
into each of the two things that needs one. The $exports
allows you to export a specific component or components from a wire spec, much like CommonJS exports
.
This approach has some nice benefits in that you can configure "private" components inside
my/trackingService.js
and they will also be created as needed, but only the trackingService
will be visible. On the downside, it's sometimes a bit more work to separate a prototype component like this into its own wire spec.
An upcoming version of wire.js will support other types of component scopes, and so will make some cases easier.