模型驱动应用中的客户端 API 执行上下文

执行上下文定义代码在其中运行的事件上下文。 当窗体或网格上发生事件时,系统会传递执行上下文。 在事件处理程序中使用它来执行各种任务,例如确定 formContext 或 gridContext 或管理保存事件。

可以通过以下方式传递执行上下文:

  • 使用 UI 定义事件处理程序:执行上下文是一个 可选 参数,可以通过事件处理程序传递给 JavaScript 库函数。 使用将执行上下文作为第一个参数选项,在处理程序属性对话框中指定函数的名称以传递事件执行上下文。 执行上下文是传递给函数的第一个参数。


执行上下文对象提供处理上下文的方法。 有关详细信息,请参阅 客户端 API 执行上下文方法参考。

异步使用上下文对象

系统传递给事件的上下文仅在事件期间按预期工作。 在事件结束后保留对上下文的引用时,可能会发生导致上下文方法出现意外行为的操作。

例如,如果你的事件处理程序调度了一个异步操作,该操作需要很长时间,而你持有对执行上下文的引用,则最终用户可能会在 Promise 解析并调用上下文方法时离开当前页面。 这种情况可能会导致诸如formContext.getAttribute(<name>).getValue()之类的方法在返回null时,即便在原始事件处理程序执行时属性已有值。

以下示例显示应添加更多检查的位置并小心,因为事件处理程序函数在事件完成后使用执行上下文。

在 Promise 中访问上下文

承诺解决后,上下文可能会以意外的方式更改。

function onLoad(executionContext) {
  const formContext = executionContext.getFormContext();
  fetch("https://www.contoso.com/").then((result) => {
    // Using formContext or executionContext here may not work as expected
    // because onLoad has already completed when the promise is resolved.
    formContext.getAttribute("name").setValue(result);
  });
}

在 await 语句之后访问上下文

在异步函数中使用 await 后,上下文可能会以意外的方式更改。

async function onLoad(executionContext) {
  const formContext = executionContext.getFormContext();
  const result = await fetch("https://www.contoso.com/");
    // Using formContext or executionContext here might not work as expected
    // because the synchronous part of onLoad has already completed.
    formContext.getAttribute("name").setValue(result);
}

在超时函数中访问上下文

使用 setTimeout 或 setInterval 延迟执行某些代码后,上下文可能会发生意外更改。

function onLoad(executionContext) {
  const formContext = executionContext.getFormContext();
    if (notReady) {
    setTimeout(() => {
            // Using formContext or executionContext here may not work as expected
            // because onLoad has already completed when this delayed function executes.
            const name = formContext.getAttribute("name").getValue();
        }, 100);
    } else {
        formContext.getAttribute("name").setValue("abc");
    }
}

客户端 API 表单上下文
客户端 API 网格上下文
功能区动作中的表单和网格上下文