Skip to content

Commit

Permalink
feat: add teardown hooks (#17)
Browse files Browse the repository at this point in the history
tgvashworth authored Mar 30, 2017
1 parent ba9bd63 commit db14fd6
Showing 3 changed files with 44 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -114,6 +114,22 @@ const { teardownEvent } = attach(Component, '.some-node', {

In this example, `teardownEvent` will be `someTeardownEvent`.

## Teardown hooks

To perform cleanup tasks around child teardown events, there are two methods you can "hook" with advice: `willTeardownChild` and `didTeardownChild`.

```js
this.before('willTeardownChild', function () {
// The childTeardownEvent has not yet fired, so you can do any extra cleanup you need
// before your child components disappear
});

this.before('didTeardownChild', function () {
// The childTeardownEvent has now fired and the child components will have run teardown.
// This is the time to do final cleanup.
});
```

## Development

To develop this module, clone the repository and run:
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -70,9 +70,17 @@ function withChildComponents() {
* Before this component's teardown, tell all the children to teardown
*/
this.before('teardown', function () {
this.willTeardownChild();
this.trigger(this.childTeardownEvent);
this.didTeardownChild();
});

/**
* These are here as hooks for advice around teardown.
*/
this.willTeardownChild = function () {};
this.didTeardownChild = function () {};

/**
* Utility method for attaching a component with teardownOn.
*
20 changes: 20 additions & 0 deletions src/with-child-components.spec.js
Original file line number Diff line number Diff line change
@@ -68,6 +68,26 @@ describe('withChildComponents', function () {
expect(window.childDidTeardown).toBe(true);
});

it('should call teardown hooks', function () {
var willTeardownChildSpy = jasmine.createSpy('willTeardownChildSpy');
var didTeardownChildSpy = jasmine.createSpy('didTeardownChildSpy');
var Parent = Component.mixin(function () {
this.after('initialize', function () {
this.after('willTeardownChild', function () {
willTeardownChildSpy();
});
this.after('didTeardownChild', function () {
didTeardownChildSpy();
});
});
});
var parent = new Parent();
parent.initialize(window.outerDiv);
parent.teardown();
expect(willTeardownChildSpy).toHaveBeenCalled();
expect(didTeardownChildSpy).toHaveBeenCalled();
});

it('should teardown the child when torn down if component uses new attributes', function () {
var parent = new Component();
parent.initialize(window.outerDiv);

0 comments on commit db14fd6

Please sign in to comment.