在Office add-in使用Shared JavaScript Runtime的技巧

51CTO 博客地址:https://blog.51cto.com/13969817

Shared JavaScript Runtime,允许Office add-in JavaScript代码在三个JavaScript Runtime运行,使用Shared JavaScript Runtime时可以简化代码:数据和功能在项目中的所有代码文件中共享。项目可以从任何代码文件访问任务窗格的DOM,包括ribbon命令和自定义函数,即使关闭了任务窗格,代码也可以继续运行,有许多新的UX特性,例如键盘快捷键,在使用shared runtime可以启用。

配置项目以使用shared Runtime

通过对manifest.xml文件应用的一些更改,将任何现有项目转换为使用Shared Runtime,我们建议遵循步骤:Configure your Office Add-in to use a shared JavaScript runtime

在配置项目之后,请确保为Shared Runtime指定了正确的需求,希望在清单中指定Shared Runtime的需求,如下面的xml所示:

<Requirements>

  <Sets DefaultMinVersion="1.1">

    <Set Name="SharedRuntime" MinVersion="1.1"/>

  </Sets>

</Requirements>

如果你的add in也为Excel实现了自定义函数,你需要同时指定Shared RuntimeCustom Function Runtime,如下面的XML所示:

<Requirements>
  <Sets DefaultMinVersion="1.1">
    <Set Name="SharedRuntime" MinVersion="1.1"/>
    <Set Name="CustomFunctionsRuntime" MinVersion="1.1"/>
  </Sets>
</Requirements>

 分享数据和功能

一旦Office Add in项目被设置为Shared Runtime,所有代码将在相同的JavaScript Runtime中运行,并可以共享数据,JavaScript函数在一个文件中可以调用另一个文件中的函数----没有边界之间的代码文件,例如,commands.js中的函数可以调用taskpane.js的函数。

下面的代码示例展示了当用户按下重置图像长度按钮时如何设置和存储全局变量。

// commands.js file 
// Import functions from taskpane.js. 
import {taskPaneUpdateImageMetrics} from "../taskpane/taskpane.js";   
 
// Handle the button press event, set global variable, and call task
// pane to update its UI. 
function btnResetImageLength(event)
{ 
  // getglobal() is a helper function yo office builds into the project.
  let g = getGlobal();
   g.imageLength=100; 
   taskPaneUpdateImageMetrics(); 
   event.completed(); 
} 
... 
 
// taskpane.js file 
// Import functions from commands.js. 
import {getGlobal} from "../commands/commands.js"; 
 
// Update element in the DOM by reading global variable value 
export function taskPaneUpdateImageMetrics()
{ 
  const g = getGlobal();
  document.getElementById("imageLength").textContent=g.imageLength; 
}

即使关闭了任务窗格也要运行代码

即使关闭了任务窗格,Shared Runtime仍将继续运行,这意味着你可以创建全局变量,并且在用户关闭任务窗格时不会丢失状态。

// You can rely on this variable to persist even if the task pane is closed 
var userName; 
function setUserName(name)
{ 
  userName = name; 
}

 此外,当任务窗格打开或者关闭时,shared runtime发送事件,处理这些事件,以便在用户打开或关闭任务窗格时采取操作,例如,你可能希望在打开任务窗格时加载或刷新数据。

Office.addin.onVisibilityModeChanged(function(args)
{
    if (args.visibilityMode = "Taskpane");
    {
        // Code that runs whenever the task pane is made visible.
        // For example, an Excel.run() that loads the names of
        // all worksheets and passes them to the task pane UI.
    }
}
);

 从任何地方访问任务窗格DOM

使用shared runtime允许你从任何代码文件访问任务窗格DOM,例如,假设add in有一个按钮,可以将add in设置为使用公制单位,代码需要更新任务窗格UI以反映状态更改,下面的示例展示了如何在commands.js中处理按钮按下事件并更新任务窗格上的复选框。

function btnSetMetric(event)
{ 
  document.getElementById('metric').checked="true"; 
  event.completed(); 
}

 相关资料:


猜你喜欢

转载自blog.51cto.com/13969817/2681327
今日推荐