Optionally a function-resource can provide a cleanup function.
Example:
import { resource } from 'ember-resources';
import { TrackedObject } from 'tracked-built-ins';
const load = resource(({ on }) => {
let state = new TrackedObject({});
let controller = new AbortController();
on.cleanup(() => controller.abort());
fetch(this.url, { signal: controller.signal })
// ...
return state;
})
Co-locate setup and teardown together. This allows you to keep "management variables" out of scope for the overall resource.
Example:
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;
});
The Application owner. This allows for direct access to traditional ember services.
Example:
resource(({ owner }) => {
owner.lookup('service:router').currentRouteName
//...
}
Allows for composition of resources.
Example:
let formatter = new Intl.DateTimeFormat("en-US", {
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
});
let format = (time: Reactive<Date>) => formatter.format(time.current);
const Now = resource(({ on }) => {
let now = cell(nowDate);
let timer = setInterval(() => now.set(Date.now()), 1000);
on.cleanup(() => clearInterval(timer));
return () => now.current;
});
const Stopwatch = resource(({ use }) => {
let time = use(Now);
return () => format(time);
});
Generated using TypeDoc
This is the type of the arguments passed to the
resource
function