UNPKG

1.39 kBJavaScriptView Raw
1import { computedLock, computedQueue, computedI } from "./computed.js";
2import {
3 isFunction,
4 hasOwnProperty,
5 HINT_DISPOSE, HINT_DEPENDS, defineHint,
6 MESSAGE_NOT_FUNCTION, throwError
7} from "./util.js";
8
9/** See lib/patella.d.ts */
10export function dispose(func, clean) {
11 if (func == null) {
12 func = computedQueue[computedI];
13 if (!func) {
14 throwError("Tried to dispose of current computed function while not running a computed function", true);
15 }
16 } else if (!isFunction(func)) {
17 throwError(MESSAGE_NOT_FUNCTION);
18 }
19
20 // Only execute if the function has not been disposed yet
21 if (!hasOwnProperty(func, HINT_DISPOSE)) {
22 // Only define disposed property if we aren't cleaning
23 if (!clean) defineHint(func, HINT_DISPOSE);
24
25 // Remove from dependant reactive objects
26 var depends = func[HINT_DEPENDS];
27 if (depends) {
28 defineHint(func, HINT_DEPENDS, clean ? [] : void 0);
29 for (var i = 0; i < depends.length; i++) {
30 depends[i](func);
31 }
32 }
33
34 // Remove from the queue if locked and pending execution
35 if (computedLock) { // Not required, but saves a `lastIndexOf` call on an empty array for like 6 bytes
36 var i = computedQueue.lastIndexOf(func);
37 if (i > computedI) computedQueue.splice(i, 1);
38 }
39 }
40
41 // Only return the function if it was specified as an argument
42 if (!computedLock) return func;
43}