From c9837474a4fdae1cb6239ed2d774736d33d692d0 Mon Sep 17 00:00:00 2001 From: Fahad Ibnay Heylaal Date: Thu, 27 Oct 2016 16:44:51 +0200 Subject: [PATCH] trigger `initialize()` method in Service and Factory with constructor options. (#35) --- docs/api/createService.md | 3 ++- src/createService.js | 2 +- test/createFactory.spec.js | 18 ++++++++++++++++++ test/createService.spec.js | 18 ++++++++++++++++++ 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/docs/api/createService.md b/docs/api/createService.md index ea6cef61..2b0a2d84 100644 --- a/docs/api/createService.md +++ b/docs/api/createService.md @@ -25,7 +25,8 @@ you can use the lifecycle method `initialize()`. import { createService } from 'frint'; export default createService({ - initialize() { + initialize(options = {}) { + // `options` contains all constructor options this.myProp = 'something'; }, myMethod() { diff --git a/src/createService.js b/src/createService.js index d8f4648c..7dff9f8b 100644 --- a/src/createService.js +++ b/src/createService.js @@ -16,7 +16,7 @@ export default function createService(extend = {}) { .forEach((prop) => (this[prop] = this[prop].bind(this))); if (typeof this.initialize === 'function') { - this.initialize(); + this.initialize(options); } } } diff --git a/test/createFactory.spec.js b/test/createFactory.spec.js index 7a03d2b1..c64c1149 100644 --- a/test/createFactory.spec.js +++ b/test/createFactory.spec.js @@ -32,4 +32,22 @@ describe('createFactory', () => { expect('myCustomFunction' in myFactoryInstance).to.be.equal(true); expect(myFactoryInstance.myCustomFunction()).to.be.equal('value'); }); + + it('triggers initialize method with constructor options', () => { + const TestFactory = createFactory({ + initialize(options) { + this.storedOptions = options; + } + }); + + const testFactoryInstance = new TestFactory({ + app: true, + foo: 'bar' + }); + + expect(testFactoryInstance.storedOptions).to.deep.equal({ + app: true, + foo: 'bar' + }); + }); }); diff --git a/test/createService.spec.js b/test/createService.spec.js index 9f4fba79..6986848e 100644 --- a/test/createService.spec.js +++ b/test/createService.spec.js @@ -42,4 +42,22 @@ describe('createService', () => { it('must bind methods to the service instance', () => { expect(myServiceInstance.returnsThis()).to.be.deep.equal(myServiceInstance); }); + + it('triggers initialize method with constructor options', () => { + const TestService = createService({ + initialize(options) { + this.storedOptions = options; + } + }); + + const testServiceInstance = new TestService({ + app: true, + foo: 'bar' + }); + + expect(testServiceInstance.storedOptions).to.deep.equal({ + app: true, + foo: 'bar' + }); + }); });