Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add on-setup #955

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion ember-resources/src/core/function-based/manager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
// @ts-ignore
import { createCache, getValue } from '@glimmer/tracking/primitives/cache';
import { assert } from '@ember/debug';
import { associateDestroyableChild, destroy, registerDestructor } from '@ember/destroyable';
import {
associateDestroyableChild,
destroy,
isDestroyed,
registerDestructor,
} from '@ember/destroyable';
// @ts-ignore
import { invokeHelper } from '@ember/helper';
// @ts-ignore
Expand Down Expand Up @@ -113,6 +118,22 @@ class FunctionResourceManager {
cleanup: (destroyer: Destructor) => {
registerDestructor(currentFn, destroyer);
},
setup: (setuper: () => void | Destructor) => {
// TODO: figure out a good option here.
// Potential options:
// - requestAnimationFrame
// - requestIdleCallback
// - "after render" (runloop schedule)
requestAnimationFrame(() => {
if (isDestroyed(currentFn)) return;

let destroyer = setuper();

if (destroyer) {
registerDestructor(currentFn, destroyer);
}
});
},
},
use,
owner: this.owner,
Expand Down
32 changes: 32 additions & 0 deletions ember-resources/src/core/function-based/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,38 @@ export type ResourceAPI = {
* })
*/
cleanup: (destroyer: Destructor) => void;

/**
* Co-locate setup and teardown together.
* This allows you to keep "management variables" out of scope
* for the overall resource.
*
* Example:
* ```js
* import { resource, cell } from 'ember-resources';
*
* const DateTime = resource(({ on }) => {
* const now = cell(new Date())
*
* on.setup(() => {
* let interval = setInterval(() => now.current = new Date(), 1000);
*
* // This function is the cleanup
* return () => clearInterval(interval);
* });
*
* on.setup(() => {
* let timeout = setTimeout(() => now.current = 0, 30_000);
*
* return () => clearTimeout(timeout);
* });
*
* return now;
* });
* ```
*
*/
setup: (setup: () => void | Destructor) => void;
};

/**
Expand Down