改变全局上下文的两种形式

287 阅读1分钟
入栈出栈
const globalState = {
  context: [],
}

function cleanup(reaction) {
  for (const dep of reaction.deps) {
      dep.delete(reaction);
  }
  reaction.dependencies.clear();
}

function createReaction(fn) {
  const reaction = {
    deps: new Set(),
  };
  try {
    cleanup(reaction);
    globalState.context.push(reaction);
    fn();
  } finally {
    globalState.context.pop();
  }
}

function subscribe(schedule, subscriptions) {
  subscriptions.add(schedule);
  schedule.deps.add(subscriptions);
}

createReaction(() => {
  const subscriptions = new Set();
  const context = globalState.context[globalState.context.length - 1];
  if (context) subscribe(context, subscriptions);
})

变换数值
const globalState = {
  context: null,
}

function cleanup(reaction) {
  for (const dep of reaction.deps) {
      dep.delete(reaction);
  }
  reaction.dependencies.clear();
}

function createReaction(fn) {
  const reaction = {
    deps: new Set(),
  };
  const preContext = globalState.context;
  try {
    cleanup(reaction);
    globalState.context = reaction;
    fn();
  } finally {
    globalState.context = preContext;
  }
}

function subscribe(schedule, subscriptions) {
  subscriptions.add(schedule);
  schedule.deps.add(subscriptions);
}

createReaction(() => {
  const subscriptions = new Set();
  const context = globalState.context;
  if (context) subscribe(context, subscriptions);
})