Pregunta

First: i'm new wirejs and its very possible i've missed something on the docs

On regular component declaration, like:

'Bnaya/App/TrackingService': {
    create: {
        module: 'Bnaya/App/TrackingService',
        args: []
    }
}

All of the components that will depend on that component using $ref, will get the same instance, so wire will be also kind of singleton mechanism (Which is good for me on most of the cases)

On some cases, i want that every dependent will get its own instance of the component, using the same component configurations.

'Bnaya/App/TrackingService': {
    create: {
        module: 'Bnaya/App/TrackingService',
        args: [],
        notASingleton: true
    }
}

I know how to get similar result using multiple components names or inline creating of instances, but that what i'm trying to avoid.

Thanks!

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top